您的位置:首页 > Web前端

Effective C# 学习笔记(四十六)对异常进行分类并逐类处理

2011-08-06 22:05 375 查看
对于异常的认识

异常并不是包括所有错误条件

抛出的异常最好是有定义的针对特殊类别的异常类型,不要总是使用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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: