详解C#编程中异常的创建和引发以及异常处理
创建和引发异常 static void CopyObject(SampleClass original) { if (original == null) { throw new System.ArgumentException("Parameter cannot be null","original"); } } 根据对象的状态,对某个对象进行不适当的调用。 class ProgramLog { System.IO.FileStream logFile = null; void OpenLog(System.IO.FileInfo fileName,System.IO.FileMode mode) {} void WriteLog() { if (!this.logFile.CanWrite) { throw new System.InvalidOperationException("Logfile cannot be read-only"); } // Else write data to the log and return. } } 方法的参数导致了异常。 static int GetValueFromArray(int[] array,int index) { try { return array[index]; } catch (System.IndexOutOfRangeException ex) { System.ArgumentException argEx = new System.ArgumentException("Index is out of range","index",ex); throw argEx; } } 异常包含一个名为 StackTrace 的属性。此字符串包含当前调用堆栈上的方法的名称,以及为每个方法引发异常的位置(文件名和行号)。 StackTrace 对象由公共语言运行时 (CLR) 从 throw 语句点开始自动创建,因此必须从堆栈跟踪的开始点引发异常。
定义异常类 程序可以引发 System 命名空间中的预定义异常类(前面注明的情况除外),或通过从 Exception 派生来创建它们自己的异常类。派生类至少应定义四个构造函数:一个是默认构造函数,一个用来设置消息属性,一个用来设置 Message 属性和 InnerException 属性。第四个构造函数用于序列化异常。新异常类应该可序列化。例如: public class InvalidDepartmentException : System.Exception { public InvalidDepartmentException() : base() { } public InvalidDepartmentException(string message) : base(message) { } public InvalidDepartmentException(string message,System.Exception inner) : base(message,inner) { } // A constructor is needed for serialization when an // exception propagates from a remoting server to the client. protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) { } } 仅当新属性提供的数据有助于解决异常时,才应将其添加到异常类。如果向派生的异常类添加了新属性,则应重写 ToString() 以返回添加的信息。
try { // Code to try goes here. } catch (SomeSpecificException ex) { // Code to handle the exception goes here. // Only catch exceptions that you know how to handle. // Never catch base class System.Exception without // rethrowing it at the end of the catch block. } try { // Code to try goes here. } finally { // Code to execute after the try block goes here. } try { // Code to try goes here. } catch (SomeSpecificException ex) { // Code to handle the exception goes here. } finally { // Code to execute after the try (and possibly catch) blocks // goes here. } 不带有 catch 或 finally 块的 try 块将导致编译器错误。 int GetInt(int[] array,int index) { try { return array[index]; } catch(System.IndexOutOfRangeException e) { throw new System.ArgumentOutOfRangeException( "Parameter index is out of range."); } } 希望在将异常传递出去进行额外处理前部分地处理异常。在下面的示例中,catch 块用于在再次引发异常之前,向错误日志添加条目。 try { // Try to access a resource. } catch (System.UnauthorizedAccessException e) { // Call a custom error logging procedure. LogError(e); // Re-throw the error. throw; } Finally 块 在下面的示例中,使用 finally 块关闭在 try 块中打开的文件。注意,在关闭文件之前要检查该文件句柄的状态。如果 try 块无法打开文件,则文件句柄仍具有值 null,并且 finally 块不会尝试关闭它。或者,如果在 try 块中成功打开该文件,则 finally 块将关闭打开的文件。 System.IO.FileStream file = null; System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:file.txt"); try { file = fileinfo.OpenWrite(); file.WriteByte(0xF); } finally { // Check for null because OpenWrite might have failed. if (file != null) { file.Close(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |