Effective C# 学习笔记(四十六)对异常进行分类并逐类处理
2011-08-06 22:05 小郝(Kaibo Hao) 阅读(368) 评论(0) 编辑 收藏 举报对于异常的认识
- 异常并不是包括所有错误条件
- 抛出的异常最好是有定义的针对特殊类别的异常类型,不要总是使用System.Exception来处理异常,这样你可以针对不同的异常进行不同的Catch操作。可以从以下方面定义(这里只是抛砖引玉):
- 找不到文件或目录
- 执行权限不足
- 丢失网络资源
创建异常的要点
- 自定义异常类必须以Exception结尾
- 自定义异常类总是继承自System.Exception类
- 实现以下四个构造器重载
// 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);
}
}
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。