Summary of common methods for parsing exception and C # processing exception

Source: Internet
Author: User

The four elements of exception handling include a class type that represents the details of the exception, a member that throws an exception class instance to the caller, a block of code that invokes the exception member, and a block of code for the caller to handle the exception that will occur. Exception class types include: base class: System.Exception; system-level exception: system.systemexception; application-level exception: System.ApplicationException.

(a). In. NET, there are the following exception classes:

(1). The exception type derived by System.SystemException:

System.accessviolationexception The exception that is thrown when attempting to read and write protected memory.
System.ArgumentException The exception that is thrown when one of the arguments supplied to the method is invalid.
System.Collections.Generic.KeyNotFoundException Specifies the exception that is thrown when the key used to access an element in the collection does not match any key in the collection.
System.IndexOutOfRangeException The exception that is thrown when an array is accessed because the element index exceeds the bounds of the array.
System.InvalidCastException The exception that is thrown because of an invalid type conversion or display conversion.
System.InvalidOperationException The exception that is thrown when a method call is not valid for the current state of an object.
System.invalidprogramexception The exception that is thrown when the program contains invalid Microsoft intermediate language (MSIL) or metadata, which usually indicates that there is a bug in the compiler for the build program.
System.IO.IOException The exception that is thrown when an I/O error occurs.
System.NotImplementedException The exception that is thrown when a requested method or operation cannot be implemented.
System.NullReferenceException The exception that is thrown when an attempt is made to manipulate an empty object reference.
System.OutOfMemoryException The exception that is thrown when there is not enough memory to continue executing the program.
System.StackOverflowException The exception that is thrown when the execution stack overflows because of too many pending method calls.

(2). The exception type derived by System.ArgumentException:

System.ArgumentNullException The exception that is thrown when a null reference is passed to a method that does not accept it as a valid parameter.
System.ArgumentOutOfRangeException The exception that is thrown when the parameter value exceeds the allowable range of values defined by the calling method.

(3). The exception type derived by System.ArithmeticException:

System.DivideByZeroException The exception that is thrown when attempting to divide an integer value or decimal value with 0.
System.notfinitenumberexception The exception that is thrown when the floating-point value is positive infinity, negative infinity, or non-numeric (NaN).
System.OverflowException The exception that is thrown when an arithmetic operation, type conversion, or conversion operation in the selected context causes an overflow.

(4). The exception type derived by System.ioexception:

System.IO.DirectoryNotFoundException The exception that is thrown when a file or part of a directory is not found.
System.IO.DriveNotFoundException The exception that is thrown when an attempt to access a drive or share is not available.
System.IO.EndOfStreamException The exception that is thrown when the read operation attempts to exceed the end of the stream.
System.IO.FileLoadException The exception that is thrown when a managed program is found but cannot load it.
System.IO.FileNotFoundException The exception that is thrown when an attempt to access a file that does not exist on disk fails.
System.IO.PathTooLongException The exception that is thrown when the path name or file name exceeds the system-defined maximum length.

(5). Other common exception types:

ArrayTypeMismatchException An attempt was made to store an object of the wrong type in an array.
BadImageFormatException The graphic is in an incorrect format.
DivideByZeroException Except for 0 exceptions.
Dllnotfoundexception The referenced DLL was not found.
FormatException Parameter format is incorrect.
Methodaccessexception An attempt was made to access a private or protected method.
MissingMemberException Access an invalid version of the DLL.
NotSupportedException The called method is not implemented in the class.
PlatformNotSupportedException This error is thrown when the platform does not support a particular property.

(b). NET Exception handling methods:

When an exception occurs, the system searches for the most recent catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched to find a try statement that contains its lexical, and the individual catch clauses associated with the Try statement are examined sequentially. If the above operation fails, in the method that called the current method, search for a try statement that contains the location of the current method call code in the lexical. This search will continue until you find a catch clause that can handle the current exception, which specifies an exception class that belongs to the same class as the run-time type that is currently throwing the exception, or a base class for the class to which the runtime type belongs. Note that the catch clause that does not specify an exception class can handle any exception.

When a matching catch clause is found, the system transfers control to the first statement of the catch clause. Before the execution of a catch clause begins, the system first executes all the finally clauses that correspond to all the try statements that are nested within the try statement that is snapped to the exception.

(1). Try block: The included code usually needs to perform some common resource cleanup operations, or it needs to be recovered from the exception, or both. A try block can also contain code that might throw an exception.

(2). Catch block: Contains code that responds to an exception that needs to be executed. If no catch type matches the thrown exception, the CLR goes to the higher layer of the call stack to search for a catch type that matches the exception.

(3). Finally block: The code that contains is the code that guarantees execution. Finally block when all code finishes executing, the thread exits the finally block and executes the statement immediately after the finally block.

(iii). Exception Common properties of the source code parsing:

(1). Message: Contains an accessible textual description that indicates the cause of the exception being thrown.

Public virtual String Message {               get {                if (_message = = null) {                    if (_classname==null) {                         _classname = Getclas SName ();                    }                     Return environment.getruntimeresourcestring ("Exception_wasthrown", _classname);                 } else {                     return _message;                }            }        

(2). Data: A reference to a "key/value pair" collection.

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-gene Rated #endif get {if (_source = = null) {Stackt                    Race 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 Modulebuild                             ER = 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;} }

(iv). Common methods for exception handling:

(1). Extracting exceptions and their internal exception stack traces

        <summary>///extract exception and its internal exception stack trace///</summary>//<param name= "Exception"        Extract exceptions </param>///<param Name= "Laststacktrace" > Last extracted stack trace (for recursion), String.Empty or null</param>        <param name= "Excount" > Number of Stacks fetched (for recursion) </param>//<returns>Syste.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 last stack trace parameter laststacktrace = laststacktrace?? String.            Empty; Adds the stack trace for the exception 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 inner exception if (ex = ex. innerexception) = null) return ex. Extractallstacktrace (String.            Format ("{0}\r\n\r\n", laststacktrace), ++excount);        return laststacktrace; }

(2). Check that the string is empty or empty, and throws an exception

        <summary>        ///check string is empty or empty and throws an exception////</summary>//        <param name= "val" > Value Test </ Param>        //<param name= "paramname" > Parameter check 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 throws an exception

        <summary>///        Check parameters are not invalid and throw an exception////</summary>//        <param name= "param" > Check values </ 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 b e null ");        }

(4). Please check that parameter 1 differs from parameter 2

       <summary>///        Please 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" + param 2Name);            }        }

(5). Check that an integer value is positive (0 or greater)

        <summary>/        //Check that an integer value 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 is greater than or equal to 0. ");        

Exception handlers (Programs): For exceptions that occur in a program, in C # is handled using an error-trapping mechanism called an "exception handler (program)", which you can think of as an exception handler (program) that can accept and handle errors when an error occurs.

Summary of common methods for parsing exception and C # processing exception

Summary of common methods for parsing exception and C # processing exception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.