当前位置: 移动技术网 > IT编程>开发语言>.net > C# 自定义异常

C# 自定义异常

2019年07月13日  | 移动技术网IT编程  | 我要评论

嘘禁止想象迅雷下载,容积率标准,凤凰卫视锵锵三人行

 

1、自定义异常类

1.1 为什么要自定义异常类

(1)没有具体系统异常相对应

(2)不希望在catch块中处理

(3)希望能明确标志错误种类的异常

1.2 自定义异常类定义步骤

继承自system.applicationexception类,并使用exception作为后缀名。

1.3 自定义异常的准则

 

 

自定义异常:

class myexception : applicationexception
    {
        public string error;
        private exception innerexception;

        public myexception() { }
        public myexception(string msg) :base(msg)
        {
            this.error = msg;
        }
        public myexception(string msg, exception innerexception):base(msg,innerexception)
        {
            this.innerexception = innerexception;
            error = msg;
        }
        public string geterror()
        {
            return error;
        }
    }

测试:

  class program
    {
        static void main(string[] args)
        {
            try
            {
                // 无参构造对象
                //throw new myexception();
                //throw new myexception("我的错误哦");
                throw new myexception("我的错误",new exception("这是exception的错误"));
            }
           
            catch (myexception e) 
            {
                //console.writeline(e.geterror());
                console.writeline(e.innerexception.message);
            }
            //*/
            /*
           //因为exception是myexception父类,所以如果这里是exception也能捕获到myexception的错误
           //前提是myexception必须初始化父类exception构造函数,即 public myexception(string msg) :base(msg)
           catch (exception e)
           {
               console.writeline(e.message);
           }
           //*/

            console.readkey();
        }
    }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网