捕获异常及自定义异常类

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) { }  

 }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值