本文描述处理和创建异常的最佳做法。
以下列表包含创建自己的异常和引发异常时应遵循的准则。
-
下面的示例显示如何读到文件尾。
class FileRead { public void ReadAll(FileStream fileToRead) { // This if statement is optional // as it is very unlikely that // the stream would ever be null. if (fileToRead == null) { throw new System.ArgumentNullException(); } int b; // Set the stream position to the beginning of the file. fileToRead.Seek(0, SeekOrigin.Begin); // Read each byte to the end of the file. for (int i = 0; i < fileToRead.Length; i++) { b = fileToRead.ReadByte(); Console.Write(b.ToString()); // Or do something else with the byte. } } } -
引发异常,而不是返回错误代码或 HRESULT。
-
通过在这些情况下返回 null,可最大程度地减小对应用的性能产生的影响。
-
引入新异常类,使程序员能够根据异常类在代码中采取不同的操作。
-
InvalidOperationException 异常。
-
ArgumentException 的类。
-
ApplicationException 类派生并没有很大意义。
-
例如:
-
如何:创建用户定义的异常。
-
Exception() ,它使用默认值。
-
Exception(String) ,它接受字符串消息。
-
Exception(String, Exception) ,它接受字符串消息和内部异常。
-
-
为避免此情况,可以两种方式部署包含异常信息的程序集:
-
将程序集放在两个应用域共享的公共应用程序基中。
- 或 -
-
如果两个应用域不共享一个公共应用程序基,则用强名称为包含异常信息的程序集签名并将其部署到全局程序集缓存中。
-
-
用户看到的错误消息派生自引发的异常的描述字符串,而不是派生自异常类。
-
例如,“记录表已溢出。”将是正确的描述字符串。
-
仅当存在附加信息有用的编程方案时,才在异常中包含附加信息(不包括描述字符串)。
-
throw 语句时需考虑这一点。
-
例如:
class FileReader { private string fileName; public FileReader(string path) { fileName = path; } public byte[] Read(int bytes) { byte[] results = FileUtils.ReadFromFile(fileName, bytes); if (results == null) { throw NewFileIOException(); } return results; } FileReaderException NewFileIOException() { string description = "My NewFileIOException Description"; return new FileReaderException(description); } }ArgumentException。
-
当异常从方法引发时,调用方应能够假定没有副作用。
- 来源:http://msdn.microsoft.com/zh-cn/library/seyhszts.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1