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);

}

}

原文地址:https://www.cnblogs.com/haokaibo/p/2129685.html