Summary of common methods for parsing exceptions and C # handling exceptions,
In. NET, an exception occurs when a Member does not complete the action that can be completed by its name claim. In an exception mechanism, exceptions are irrelevant to the occurrence frequency of a specific event.
Four elements of exception handling include: A class type that indicates exception details; a member that raises an exception class instance to the caller; a code block that calls an exception Member of the caller; A piece of code block for the caller to handle exceptions. Exception types include: base class: System. Exception; System-level Exception: System. SystemException; application-level Exception: System. ApplicationException.
(1). There are the following exception classes in. NET:
(1). Exception types derived from System. SystemException:
| System. AccessViolationException |
Exceptions that occur when attempting to read and write protected memory. |
| System. ArgumentException |
Exception thrown when one of the parameters provided to the method is invalid. |
| System. Collections. Generic. KeyNotFoundException |
Specifies the exception caused when the key used to access the element in the set does not match any key in the set. |
| System. IndexOutOfRangeException |
When accessing an array, an exception occurs because the element index exceeds the array boundary. |
| System. InvalidCastException |
Exception caused by invalid type conversion or display conversion. |
| System. InvalidOperationException |
The exception that is thrown when the method call is invalid for the current state of the object. |
| System. InvalidProgramException |
An exception that occurs when the program contains an invalid Microsoft intermediate language (MSIL) or metadata, which usually indicates a bug in the compiler of the program. |
| System. IO. IOException |
An I/O error occurs. |
| System. NotImplementedException |
The exception that is thrown when the request method or operation cannot be implemented. |
| System. NullReferenceException |
Exception that is thrown when an empty object reference is attempted. |
| System. OutOfMemoryException |
Exceptions that occur when there is not enough memory to continue executing the program. |
| System. StackOverflowException |
An exception that occurs when the execution stack overflows due to too many pending method calls. |
(2). Exception types derived from System. ArgumentException:
| System. ArgumentNullException |
An exception occurs when an empty reference is passed to a method that does not accept it as a valid parameter. |
| System. ArgumentOutOfRangeException |
An exception occurs when the value of the parameter exceeds the allowed value range defined by the called method. |
(3). Exception types derived from System. ArithmeticException:
| System. DivideByZeroException |
An exception is thrown when a zero-division integer or decimal value is used. |
| System. NotFiniteNumberException |
An exception is thrown when the floating point value is positive infinity, negative infinity, or non-Numeric (NaN. |
| System. OverflowException |
Overflow caused by arithmetic, type conversion, or conversion operations in the selected context. |
(4). Exception types derived from System. IOException:
| System. IO. DirectoryNotFoundException |
Exception thrown when a part of the file or directory cannot be found. |
| System. IO. DriveNotFoundException |
The exception that is thrown when the drive or share is not available. |
| System. IO. EndOfStreamException |
An exception occurs when a read operation attempts to exceed the end of the stream. |
| System. IO. FileLoadException |
Exceptions that occur when a hosted program is found but cannot be loaded. |
| System. IO. FileNotFoundException |
Exception thrown when an attempt to access a non-existent file on the disk fails. |
| System. IO. PathTooLongException |
An exception occurs when the path name or file name exceeds the maximum length defined by the system. |
(5). Other common exception types:
| ArrayTypeMismatchException |
An Error Type object is stored in the array. |
| BadImageFormatException |
Incorrect image format. |
| DivideByZeroException |
Zero division exception. |
| DllNotFoundException |
The referenced dll cannot be found. |
| FormatException |
The parameter format is incorrect. |
| MethodAccessException |
Attempts to access private or protected methods. |
| MissingMemberException |
Access an invalid version of dll. |
| NotSupportedException |
The called method is not implemented in the class. |
| PlatformNotSupportedException |
This error is thrown when the platform does not support a specific attribute. |
(2). NET exception handling method:
When an exception occurs, the system searches for the nearest catch clause that can handle the exception (determined based on the runtime type of the exception ). First, search for the current method to find a try statement that contains the lexical form, and examine the catch clauses associated with the try statement in order. If the preceding operation fails, search for the try statement that contains the location of the Code called by the current method in the method that calls the current method. This search will continue until the catch clause that can handle the current exception is found (this clause specifies an exception class, it belongs to the same class as the runtime type that causes the exception or a base class of the runtime type ). Note that the catch clause of the exception class is not specified to handle any exceptions.
After a matched catch clause is found, the system transfers the control to the first statement of the catch clause. Before the execution of the catch clause starts, the system will first execute all the finally clauses nested in all try statements in the try statements that capture the exception in order.
(1). try block: The contained Code usually requires some general resource cleanup operations, recovery from exceptions, or both. The try block can also contain code that may throw exceptions.
(2). catch Block: contains the code to be executed in response to an exception. If no catch type matches the thrown exception, the CLR will call the higher layer of the stack to search for a catch type that matches the exception.
(3). finally block: The included code is the code that will be executed. After all the code of the finally block is executed, the thread exits the finally block and runs the statement following the finally block.
(3) source code parsing of common properties of. Exception:
(1). Message: Contains auxiliary text instructions, indicating the cause of the exception.
public virtual String Message { get { if (_message == null) { if (_className==null) { _className = GetClassName(); } return Environment.GetRuntimeResourceString("Exception_WasThrown", _className); } else { return _message; } } }
(2). Data: a reference to a "key/value pair" set.
public virtual IDictionary Data { [System.Security.SecuritySafeCritical] // auto-generated get { if (_data == null) if (IsImmutableAgileException(this)) _data = new EmptyReadOnlyDictionaryInternal(); else _data = new ListDictionaryInternal(); return _data; } }
(3). Source: contains the name of the Assembly that generated the exception.
public virtual String Source { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif get { if (_source == null) { StackTrace st = new StackTrace(this,true); if (st.FrameCount>0) { StackFrame sf = st.GetFrame(0); MethodBase method = sf.GetMethod(); Module module = method.Module; RuntimeModule rtModule = module as RuntimeModule; if (rtModule == null) { System.Reflection.Emit.ModuleBuilder moduleBuilder = module as System.Reflection.Emit.ModuleBuilder; if (moduleBuilder != null) rtModule = moduleBuilder.InternalModule; else throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeReflectionObject")); } _source = rtModule.GetRuntimeAssembly().GetSimpleName(); } } return _source; } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif set { _source = value; } }
(4). Common Methods for exception handling:
(1). Extract exceptions and internal exception stack traces
/// <Summary> /// extract the exception and its internal exception stack trace // </summary> /// <param name = "exception"> extract the exception </param> /// <param name = "lastStackTrace"> last extracted stack trace (for recursion ), string. empty or null </param> /// <param name = "exCount"> Number of extracted stacks (for recursion) </param> /// <returns> limit E. string </returns> public static string ExtractAllStackTrace (this Exception exception, string lastStackTrace = null, int exCount = 1) {var ex = exception; const string EntryFormat = "# {0 }:{ 1} \ r \ n {2}"; // fix the last stack trace parameter lastStackTrace = lastStackTrace ?? String. empty; // Add the stack trace lastStackTrace + = string. format (entryFormat, exCount, ex. message, ex. stackTrace); if (exception. data. count> 0) {lastStackTrace + = "\ r \ n Data:"; foreach (var item in exception. data) {var entry = (DictionaryEntry) item; lastStackTrace + = string. format ("\ r \ n \ t {0 }:{ 1}", entry. key, exception. data [entry. key]) ;}// recursively add an internal exception if (ex = ex. innerException )! = Null) return ex. ExtractAllStackTrace (string. Format ("{0} \ r \ n", lastStackTrace), ++ exCount); return lastStackTrace ;}
(2) check whether the string is null or empty and throw an exception
/// <Summary> /// check whether the string is empty or empty, and throw an exception /// </summary> /// <param name = "val"> value test </param> /// <param name = "paramName"> Parameter check the name </param> public static void CheckNullOrEmpty (string val, string paramName) {if (string. isNullOrEmpty (val) throw new ArgumentNullException (paramName, "Value can't be null or empty ");}
(3). Check that the parameter is not invalid and throw an exception.
/// <Summary> /// check whether the parameter is invalid, and throw an exception /// </summary> /// <param name = "param"> check value </param> /// <param name = "paramName"> Parameter name </param> public static void CheckNullParam (object param, string paramName) {if (param = null) throw new ArgumentNullException (paramName, paramName + "can't be null ");}
(4). Check that parameter 1 is different from parameter 2.
/// <Summary> /// check that parameter 1 is different from parameter 2 /// </summary> /// <param name = "param1"> value 1 test </ param> /// <param name = "param1Name"> name of value 1 </param> // <param name = "param2"> value 2 to test </param> /// <param name = "param2Name"> name of vlaue 2 </param> public static void CheckDifferentsParams (object param1, string param1Name, object param2, string param2Name) {if (param1 = param2) {throw new ArgumentException (param1Name + "can't be the same as" + param2Name, param1Name + "and" + param2Name );}}
(5) Check whether an integer is positive (0 or greater)
/// <Summary> /// check whether an integer is positive (0 or greater) /// </summary> /// <param name = "val"> integer test </param> public static void PositiveValue (int val) {if (val <0) throw new ArgumentException ("The value must be greater than or equal to 0. ");}
Exception processor (Program): in C #, an error capture mechanism called "exception processor (Program)" is used to handle exceptions in a program, you can think that the exception processor (Program) is the receiver and handler that can accept and handle errors when errors occur.