在.NET中,异常是指成员没有完成它的名称宣称可以完成的行动。在异常的机制中,异常和某件事情的发生频率无关。

异常处理四要素包括:一个表示异常详细信息的类类型;一个向调用者引发异常类实例的成员;调用者的一段调用异常成员的代码块;调用者的一段处理将要发生异常的代码块。异常类类型包括:基类:System.Exception;系统级异常:System.SystemException;应用程序级异常:System.ApplicationException。

(一).在.NET中有如下的异常类:

(1).由System.SystemException派生的异常类型:

System.AccessViolationException在试图读写受保护内存时引发的异常。System.ArgumentException在向方法提供的其中一个参数无效时引发的异常。System.Collections.Generic.KeyNotFoundException指定用于访问集合中元素的键与集合中的任何键都不匹配时所引发的异常。System.IndexOutOfRangeException访问数组时,因元素索引超出数组边界而引发的异常。System.InvalidCastException因无效类型转换或显示转换引发的异常。System.InvalidOperationException当方法调用对于对象的当前状态无效时引发的异常。System.InvalidProgramException当程序包含无效Microsoft中间语言(MSIL)或元数据时引发的异常,这通常表示生成程序的编译器中有bug。System.IO.IOException发生I/O错误时引发的异常。System.NotImplementedException在无法实现请求的方法或操作时引发的异常。System.NullReferenceException尝试对空对象引用进行操作时引发的异常。System.OutOfMemoryException没有足够的内存继续执行程序时引发的异常。System.StackOverflowException挂起的方法调用过多而导致执行堆栈溢出时引发的异常。

(2).由System.ArgumentException派生的异常类型:

System.ArgumentNullException当将空引用传递给不接受它作为有效参数的方法时引发的异常。System.ArgumentOutOfRangeException当参数值超出调用的方法所定义的允许取值范围时引发的异常。

(3).由System.ArithmeticException派生的异常类型:

System.DivideByZeroException试图用零除整数值或十进制数值时引发的异常。System.NotFiniteNumberException当浮点值为正无穷大、负无穷大或非数字(NaN)时引发的异常。System.OverflowException在选中的上下文中所进行的算数运算、类型转换或转换操作导致溢出时引发的异常。

(4).由System.IOException派生的异常类型:

System.IO.DirectoryNotFoundException当找不到文件或目录的一部分时所引发的异常。System.IO.DriveNotFoundException当尝试访问的驱动器或共享不可用时引发的异常。System.IO.EndOfStreamException读操作试图超出流的末尾时引发的异常。System.IO.FileLoadException当找到托管程序却不能加载它时引发的异常。System.IO.FileNotFoundException试图访问磁盘上不存在的文件失败时引发的异常。System.IO.PathTooLongException当路径名或文件名超过系统定义的最大长度时引发的异常。

(5).其他常用异常类型:

ArrayTypeMismatchException试图在数组中存储错误类型的对象。BadImageFormatException图形的格式错误。DivideByZeroException除零异常。DllNotFoundException找不到引用的dll。FormatException参数格式错误。MethodAccessException试图访问私有或者受保护的方法。MissingMemberException访问一个无效版本的dll。NotSupportedException调用的方法在类中没有实现。PlatformNotSupportedException平台不支持某个特定属性时抛出该错误。

(二)..NET的异常处理方式:

发生异常时,系统将搜索可以处理该异常的最近的catch子句(根据该异常的运行时类型来确定)。首先,搜索当前的方法以查找一个词法上包含着它的try语句,并按顺序考察与该try语句相关联的各个catch子句。如果上述操作失败,则在调用了当前方法的方法中,搜索在词法上包含着当前方法调用代码位置的try语句。此搜索将一直进行下去,直到找到可以处理当前异常的catch子句(该子句指定一个异常类,它与当前引发该异常的运行时类型属于同一个类或是该运行时类型所属类的一个基类)。注意,没有指定异常类的catch子句可以处理任何异常。

找到匹配的catch子句后,系统将把控制转移到该catch子句的第一条语句。在catch子句的执行开始前,系统将首先按顺序执行嵌套在捕捉到该异常的try语句里面的所有try语句所对应的全部finally子句。

(1).try块:包含的代码通常需要执行一些通用的资源清理操作,或者需要从异常中恢复,或者两者都需要。try块还可以包含也许会抛出异常的代码。

(2).catch块:包含的是响应一个异常需要执行的代码。如果没有任何捕捉类型与抛出的异常匹配,CLR会去调用栈的更高一层搜索一个与异常匹配的捕捉类型。

(3).finally块:包含的代码是保证会执行的代码。finally块所有代码执行完毕后,线程退出finally块,执行紧跟在finally块之后的语句。

(三).Exception的常用属性的源码解析:

(1).Message:包含辅助性文字说明,指出抛出异常的原因。

publicvirtualStringMessage{get{if(_message==null){if(_className==null){_className=GetClassName();}returnEnvironment.GetRuntimeResourceString("Exception_WasThrown",_className);}else{return_message;}}}

(2).Data:对一个“键/值对”集合的引用。

publicvirtualIDictionaryData{[System.Security.SecuritySafeCritical]//auto-generatedget{if(_data==null)if(IsImmutableAgileException(this))_data=newEmptyReadOnlyDictionaryInternal();else_data=newListDictionaryInternal();return_data;}}

(3).Source:包含生成异常的程序集名称。

publicvirtualStringSource{#ifFEATURE_CORECLR[System.Security.SecurityCritical]//auto-generated#endifget{if(_source==null){StackTracest=newStackTrace(this,true);if(st.FrameCount>0){StackFramesf=st.GetFrame(0);MethodBasemethod=sf.GetMethod();Modulemodule=method.Module;RuntimeModulertModule=moduleasRuntimeModule;if(rtModule==null){System.Reflection.Emit.ModuleBuildermoduleBuilder=moduleasSystem.Reflection.Emit.ModuleBuilder;if(moduleBuilder!=null)rtModule=moduleBuilder.InternalModule;elsethrownewArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeReflectionObject"));}_source=rtModule.GetRuntimeAssembly().GetSimpleName();}}return_source;}#ifFEATURE_CORECLR[System.Security.SecurityCritical]//auto-generated#endifset{_source=value;}}

(四).异常处理的常用方法:

(1).提取异常及其内部异常堆栈跟踪

///<summary>///提取异常及其内部异常堆栈跟踪///</summary>///<paramname="exception">提取的例外</param>///<paramname="lastStackTrace">最后提取的堆栈跟踪(对于递归),String.Emptyornull</param>///<paramname="exCount">提取的堆栈数(对于递归)</param>///<returns>Syste.String</returns>publicstaticstringExtractAllStackTrace(thisExceptionexception,stringlastStackTrace=null,intexCount=1){varex=exception;conststringentryFormat="#{0}:{1}\r\n{2}";//修复最后一个堆栈跟踪参数lastStackTrace=lastStackTrace??string.Empty;//添加异常的堆栈跟踪lastStackTrace+=string.Format(entryFormat,exCount,ex.Message,ex.StackTrace);if(exception.Data.Count>0){lastStackTrace+="\r\nData:";foreach(variteminexception.Data){varentry=(DictionaryEntry)item;lastStackTrace+=string.Format("\r\n\t{0}:{1}",entry.Key,exception.Data[entry.Key]);}}//递归添加内部异常if((ex=ex.InnerException)!=null)returnex.ExtractAllStackTrace(string.Format("{0}\r\n\r\n",lastStackTrace),++exCount);returnlastStackTrace;}

(2).异常处理常用方法:

///<summary>///检查字符串是空的或空的,并抛出一个异常///</summary>///<paramname="val">值测试</param>///<paramname="paramName">参数检查名称</param>publicstaticvoidCheckNullOrEmpty(stringval,stringparamName){if(string.IsNullOrEmpty(val))thrownewArgumentNullException(paramName,"Valuecan'tbenullorempty");}///<summary>///请检查参数1不同于参数2///</summary>///<paramname="param1">值1测试</param>///<paramname="param1Name">nameofvalue1</param>///<paramname="param2">value2totest</param>///<paramname="param2Name">nameofvlaue2</param>publicstaticvoidCheckDifferentsParams(objectparam1,stringparam1Name,objectparam2,stringparam2Name){if(param1==param2){thrownewArgumentException(param1Name+"can'tbethesameas"+param2Name,param1Name+"and"+param2Name);}}///<summary>///检查一个整数值是正的(0或更大)///</summary>///<paramname="val">整数测试</param>publicstaticvoidPositiveValue(intval){if(val<0)thrownewArgumentException("Thevaluemustbegreaterthanorequalto0.");}

异常处理器(程序):对于程序中出现的异常,在C#中是使用一种被称为“异常处理器(程序)”的错误捕获机制来进行处理的, 你可以认为异常处理器(程序)就是发生错误时,能够接受并处理错误的接受者和处理。