zoukankan      html  css  js  c++  java
  • Effective C# 学习笔记(四十六)对异常进行分类并逐类处理

    对于异常的认识

    1. 异常并不是包括所有错误条件
    2. 抛出的异常最好是有定义的针对特殊类别的异常类型,不要总是使用System.Exception来处理异常,这样你可以针对不同的异常进行不同的Catch操作。可以从以下方面定义(这里只是抛砖引玉):
      1. 找不到文件或目录
      2. 执行权限不足
      3. 丢失网络资源

     

    创建异常的要点

    1. 自定义异常类必须以Exception结尾
    2. 自定义异常类总是继承自System.Exception
    3. 实现以下四个构造器重载

    // Default constructor

    public Exception();

     

    // Create with a message.

    public Exception(string);

     

    // Create with a message and an inner exception.

    public Exception(string, Exception);

     

    // Create from an input stream. 支持序列化的

    protected Exception(SerializationInfo, StreamingContext);

     

    举例:

    [Serializable]

    public class MyAssemblyException :Exception

    {

    public MyAssemblyException() : base()

    {

    }

    public MyAssemblyException(string s) : base(s)

    {

    }

    public MyAssemblyException(string s, Exception e) : base(s, e)

    {

    }

    //注意这里的可序列化的构造函数用了protected关键字,限制了访问权限

    protected MyAssemblyException( SerializationInfo info, StreamingContext cxt) : base(info, cxt)

    {

    }

    }

     

    这里特别说下,带有内部异常参数的构造器重载,对于调用地方类库的方法的时候,要捕获地方的异常,并把其包装到自己的异常中进行封装抛出:

    public double DoSomeWork()

    {

    try {

    // This might throw an exception defined

    // in the third party library:

    return ThirdPartyLibrary.ImportantRoutine();

    } catch(ThirdPartyException e)

    {

    string msg =

    string.Format("Problem with {0} using library",ToString());

    throw new DoingSomeWorkException(msg, e);

    }

    }

  • 相关阅读:
    Centos7下安装oracle 11g,弹窗不显示或者显示太小
    SQLserver登陆报错
    centos7配置网易yum源
    python ----django---打包重用
    python打包exe文件
    Acwing-198-反素数(约数, 数学)
    Acwing-197-阶乘分解(质数)
    Acwing-196-质数距离(素数区间筛法)
    Acwing-169-数独2(搜索, 剪枝)
    Acwing-168-生日蛋糕(搜索, 剪枝)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2129685.html
Copyright © 2011-2022 走看看