教学-46 异常

曾英-C#教学-46 异常

目录

  • 了解什么是异常
  • 掌握异常的编程的三种结构
    • 捕获异常--try-catch结构
    • 收尾工作--try-catch-finally结构
    • 抛出异常--throw语句

1\异常概述

image

  • 可以避免程序崩溃

1.1\异常的捕获--try-catch结构

  • catch可以只有一个/多个
  • 分母为零程序崩溃只针对于整形,实型是不会报错的
class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Console.WriteLine("请输入分母:");
                int denominator = Convert.ToInt32(Console.ReadLine());
                double result = 100 / denominator;
                Console.WriteLine("结果:100/{0}={1}", denominator, result);
            }
            //这里的异常名都是系统自带的
            catch (DivideByZeroException)
            { Console.WriteLine("分母不能为零"); }
            catch (FormatException)
            { Console.WriteLine("格式错误!"); }
        }
    }
}

  

1.2\收尾工作--try-catch-finally结构

  • finally:总是执行的,起到收尾的作用.
class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Console.WriteLine("请输入分母:");
                int denominator = Convert.ToInt32(Console.ReadLine());
                double result = 100 / denominator;
                Console.WriteLine("结果:100/{0}={1}", denominator, result);
            }
            //这里的异常名都是系统自带的
            catch (DivideByZeroException)
            { Console.WriteLine("分母不能为零"); }
            catch (FormatException)
            { Console.WriteLine("格式错误!"); }
            finally
            { Console.WriteLine("这是finally块"); }
        }
    }

  

1.3\抛出异常--throw语句

class Program
    {
        
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("请输入一个0-10之间的整数:");
                int number = Convert.ToInt32(Console.ReadLine());
                if (number < 0 || number > 10)
                { throw new IndexOutOfRangeException(); }//这个和catch中的关键字是一样的
                else
                { Console.WriteLine("你输入的整数是:{0}", number); }
            }
            catch (IndexOutOfRangeException)
            { Console.WriteLine("超出范围"); }
            finally{Console.WriteLine("谢谢");}
        }

    }

  

posted @ 2018-02-02 00:05  泮聪  阅读(126)  评论(0编辑  收藏  举报