捕获异常及自定义异常类

来源:互联网 发布:最新社交软件 编辑:程序博客网 时间:2024/06/04 19:05
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace 捕获异常
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
         
              Console.WriteLine("请输入一个非负数:");
                int number = Convert.ToInt32(Console.ReadLine());//可能产生格式异常
                double root;
                if (number < 0)
                {
                    throw new NegativeNumberExeption();//可能产生负数开平方根的异常
                    // throw new NegativeNumberExeption("负数不能开平方!");//可能产生负数开平方根的异常
                }
                else
                {
                    root = Math.Sqrt(number);
                }
               
                Console.WriteLine("结果:{0}", root);

            }
            catch (NegativeNumberExeption e)//捕获负数开平方根的异常
            {
                Console.WriteLine(e.Message);//属性message指出异常的内容
                Console.WriteLine(e.StackTrace);//属性StackTrace指出异常产生在哪个位置
            }
            catch (FormatException e)//捕获格式异常
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                Console.WriteLine("运算结束!");//finally :不管是否出现异常,都会运行
            }

        }

     class NegativeNumberExeption : ApplicationException //自定义一个负数的异常    

 {
       public NegativeNumberExeption() : base("对负数进行非法操作") { }        //自行查看上一篇base关键字的用法
       public NegativeNumberExeption(string message) : base(message) { }  

 }

    }
}
0 0
原创粉丝点击