C#基础知识学习——异常处理(十)

异常处理可以提高代码的健壮性,一般用try catch语句:

             try
            {
    
    
               //函数体
            }
            catch (Exception e)
            {
    
    

                Console.WriteLine("异常处理===》" + e.Message.ToString());
            }

举个栗子

         public static void Test(int a, int b)
        {
    
    
            try
            {
    
    
                int x = a / b;
                Console.WriteLine(x);
            }
            catch (Exception e)
            {
    
    

                Console.WriteLine("异常处理===》" + e.Message.ToString());
            }

        }

也可以自己定义异常,继承Exception类即可

        /// <summary>
        /// 自定义异常:继承Exception类即可
        /// </summary>
        public class CustonmeEx : Exception
        {
    
    
            //创建构造函数并覆盖父类中的异常信息
            public CustonmeEx(string msg) : base(msg)
            {
    
    
                Exception exception = new Exception(msg);
            }

        }
        //自定义异常处理
        public static void Test1(int a, int b)
        {
    
    
            try
            {
    
    
                int x = a / b;
                Console.WriteLine(x);
            }
            catch (Exception e)
            {
    
    
                throw new CustonmeEx("除数为零");
            }

        }
         public MainWindow()
        {
    
    
            InitializeComponent();
            举例1:一般异常处理
           // Test(1, 0);
            //自定义异常使用与多异常捕获(具体异常放到Exception异常上面)
            try
            {
    
    
                举例2:自定义异常处理
               // Test1(1, 0);

               // //举例3:自定义异常使用与多异常捕获
                Test1(1, 2);
                int.Parse("aaa");

            }
            catch (CustonmeEx e)
            {
    
    
                Console.WriteLine("自定义异常的消息===》" + e.Message);
            }
            catch (Exception ed)
            {
    
    
                Console.WriteLine("API异常的消息===》" + ed.Message);
            }
            finally//执行是否出现异常都调用的部分,除非在catch中有抛出异常的语句
            {
    
    
                Console.WriteLine("清理资源");
            }
        }

猜你喜欢

转载自blog.csdn.net/weixin_45496521/article/details/127876432