异常处理

一、程序运行时产生的错误通过使用一种称为异常(Exception)的机制在程序中传递,通过异常处理(Exception Handling)有助于处理程序运行过程中发生的意外或异常情况;异常可由CLR和客户端代码抛出(Throw),抛出的异常会在调用堆栈中传递,直到遇到可以捕获该异常的语句进行处理并中止传递,未捕获的异常会由系统终止进程并由系统的通用异常处理程序处理,通常会显示一个包含异常信息的对话框;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 定制异常
{
   
    class Program
    {
        public static double MyFunc(double divident, double divisor)
        { 
            if(divident==0)
            {
                throw new MyException { MyInfo = "亲爱的,被除数不能为零哦!" };
            }
            else
            {
                return divident / divisor;
            }
        }
        static void Main(string[] args)
        {
            double x = 0;
            double y = 10;
          try
            {
                MyFunc(x, y);
            }catch(MyException e)
            {
                Console.WriteLine("MyException Throw:" + e.MyInfo);

            }catch(Exception e)
            {
                Console.WriteLine("UnKnow Exception:" + e);
                throw;
            }

            finally
            {
                Console.WriteLine("捕获异常结束!");
            }

            Console.ReadLine();
            
        }
    }

    class MyException:Exception
    {
        public string MyInfo;
    }
}
原文地址:https://www.cnblogs.com/Mr-Prince/p/12204853.html