异常处理语句

1.  定义异常

2.  定义异常类,使用异常类

3.  使用异常类,捕捉异常

 

1.  定义异常类   继承Exception,调用父类有参构造函数base(message)

 class BankException : Exception
    {
        public BankException(string message) : base(message)   //有参数的构造函数
        {
            this.message = message;
            File.AppendAllText(@"C:\Users\LJK\Pictures\新建文件夹\a.log", DateTime.Now+":"+message+"\r\n");    //错误存放文件路径
        }
        string message = "银行业务逻辑错误!";
        public string Message
        {
             get
            {
                return message;
            }
        }
    }

2.  定义异常类,使用异常类

 

class Bank
    {
        public void Out()
        {
            Console.WriteLine("请录入取款金额:");
            double outmoney = double.Parse(Console.ReadLine());
            if (outmoney > 1000)
            {

                throw new BankException("取款金额不能大于存款金额");
            }
        }
    }

 

3.  使用异常类,捕捉异常

 

 //使用业务类,捕捉异常
        static void Main(string[] args)
        {  
            //捕捉异常
            try
            {
                int i = 10;
                int j = 0;
                int k = i / j;
                //DivideByZeroException
                Bank bank = new Bank();
                bank.Out();
            }
            catch(Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }

 

posted @ 2017-02-16 16:08  刘靖凯  阅读(345)  评论(0编辑  收藏  举报