C # Exception Handling summary

Source: Internet
Author: User

    1. Exception class Analysis
    2. Common exception classes
    3. Exception capture
    4. Exception handling principles and recommendations

The SystemException class inherits exception, which is the base class for all other exception classes in the System namespace, and the first thing I look at when catching an exception is exception object information. Exception important members such as
Write a picture description here
1.Message Properties: Error message that causes an exception

[__dynamicallyinvokable] Public Virtual stringmessage{[__dynamicallyinvokable]Get    {        if( This. _message! =NULL)        {            return  This. _message; }        if( This. _classname = =NULL)        {             This. _classname = This.        GetClassName (); }        returnEnvironment.getruntimeresourcestring ("Exception_wasthrown",New Object[] { This. _classname}); }}

The message property is a read-only property, and Getruntimeresourcestring is the Get runtime resource string. The returned string is an error message or an empty string that produces the cause of the exception.


2.Data: Collection of key/value pairs for other exception information

 Public VirtualIDictionary Data {Get{                if(_data = =NULL)                   if(Isimmutableagileexception ( This))
_data =Newemptyreadonlydictionaryinternal (); Else_data=Newlistdictionaryinternal (); return_data; } }

3.StackTrace: Method name and signature called before an exception occurs

 Public Static string stacktrace{    [securitysafecritical]    get    {         New  EnvironmentPermission (permissionstate.unrestricted). Demand ();         return Getstacktrace (nulltrue);}    }

4.Source property: Contains the name of the application or object that generated the exception
5.TargetSite property: Method that throws the current exception
6.GetBaseException method: Returns System.Exception, which is the "base" class for all exception classes.

Common exception classes

There are a lot of exception types, and they are all inherited from SystemException, these types of exceptions are roughly divided into the following 1. Related to array Collection 2. Related to member access 3. Related to parameters 4. Related to arithmetic 5.IO 6. Of course there are other exceptions.
1. Related to Array collection
IndexOutOfRangeException class: Exception thrown by index out of range
ArrayTypeMismatchException class: An array collection stores an exception thrown by an incorrect data type
Rankexception class: Handling Exceptions thrown by dimension errors
2.IO-related exceptions
An IO-related exception is inherited from the IOException class, which handles the exception that is thrown when a file input and output operation is performed, and the 5 direct derived classes of the IOException class are as follows.
DirectoryNotFoundException class: The exception that is thrown when the specified directory is not found.
FileNotFoundException class: The exception that is thrown when a file is not found.
EndOfStreamException class: The exception that is thrown when processing the end of a stream and continuing to read the data.
FileLoadException class: The exception that is thrown when a file cannot be loaded.
PathTooLongException class: The exception that is thrown when the file name is too long.
3. member access-related exceptions
Exceptions associated with member access are inherited from the Memberaccessexception class, which inherits from SystemException.
Fileaccessexception: Exception thrown when accessing a field member failed
Methodaccessexception: Access method member failed throwing exception
MissingMemberException: The exception that is thrown by the member does not exist
4. Parameter-related exceptions
Exception class ArgumentException that are associated with parameters are inherited from SystemException, and exceptions are handled when parameters are passed to a method member
ArgumentOutOfRangeException: An exception that is thrown when a parameter is not in a given range
ArgumentNullException: Exception thrown in case of NULL (null not allowed) argument
5. Arithmetic-related
The arithmeticexception exception class is used to handle arithmetic-related exceptions, and its related subclasses are as follows
DivideByZeroException: Integer decimal Attempt to divide the exception thrown by 0 (dividend cannot be 0)
NotFiniteNumberException: Exceptions thrown by infinity or non-negative values in a floating-point operation
6. Other anomalies
NullReferenceException: When an object is not instantiated and references the exception that is thrown
InvalidOperationException: Throws an exception when the calling object's current state of the opposing method is invalid
InvalidCastException: Handling Exceptions thrown during type conversion
OutOfMemoryException: Handling exceptions thrown by insufficient memory
StackOverflowException: Handling errors caused by stack overflow

Exception capture

The try and catch blocks provided in C # provide a structured exception handling scheme in which all possible exceptions must be properly handled, and the try catch itself does not affect the performance of the system, and the try catch does not affect the performance of the system when no exception occurs. The time to be affected is when an exception occurs.
The keyword try Catch finally. Executes the statement inside the try and is caught by a catch if an exception is thrown. The statement inside the finally will be executed regardless of the exception. Another infrequently used throw keyword: When a problem occurs, the program throws an exception.

classProgram {Static voidMain (string[] args) {Dividenumber div=NewDividenumber (); Div. Dividemethod (2,0);        Console.readkey (); }    }    classDividenumber {intresult;  PublicDividenumber () {result=0; }         Public voidDividemethod (intAintb) {Try{result= A/b; }            Catch(DivideByZeroException e) {Console.WriteLine ("exception, the divisor cannot be 0,e.message:"+e.message); }            finally{Console.WriteLine ($"The result of {a} divided by {b} is"+result); }        }    }
Exception handling principles and recommendations

In the actual development, how to write the exception, or the stability and fault tolerance of the system have certain requirements.

To catch a specific exception
When catching an exception, we often habitually write catch (Exception ex), this is not a specific exception, it is best to be specific to ArgumentException, FormatException and other exception classes, do not throw "new Exception () ”
Nothing is done in catch, exception is thrown to the top layer
This situation may be more common when writing your demo, and do not do anything under the code of the catch (Exception ex). Remember that the exception you want to throw at the top level
Rational use of finally blocks
The finally keyword is that whatever type of exception is thrown will be executed, and most of the code executed under the finally block can be written in the catch. So what is the best use of the finally keyword, such as cleaning up resources, closing the stream, replying to status, and so on.
The exception to be thrown is recorded.
Of course, the exception that occurs in the program is not all to be recorded, and some anomalies are recorded to facilitate the analysis of specific problems. Some log library log4net, EIF ...
Do not log only the value of exception.message, you need to record exception.tostring ()
Just in front of the example, I printed the E. Message, just the output "try dividing by 0", the error message is not specific and is not recommended. The ToString method contains StackTrace, inner exception information, message ... usually this information is more important than just one message
Do not use "throw exception" as a result of function execution
The "throw exception" should be thrown at the top level, but not as a result of the method's execution, and the result of the method cannot be an exception class.
Each thread must contain a try/catch block
When you create a child thread to perform a task, the main thread does not know the exception of the child thread, so each thread needs a try, catch.
Comments from "Code thinker"
I also thought about how to effectively practice exception handling in project teams when I was working as a project manager for a C # project.
First, exception handling should be part of the system design specification, not just a technical implementation, but in the system design documentation.
As part of the design documentation, exception handling should focus on system fault tolerance and stability (as mentioned by the landlord). Then, in accordance with this Statute, we will discuss and select the various technical rules used in exception handling.
For example, when designing a service, you must have exception handling at the invocation interface of the service, or any harmful data passed by the client may cause the server to hang.
For example, the handling of exceptions in the system design, must have a clear explanation, not casually in which module to handle the exception.
The above is my personal experience, but also hope to go through a lot of friends to communicate.

Zhang Lin title: C # Exception Handling summary
Original address: http://blog.csdn.net/kebi007/article/details/78221083 reproduced at random to indicate the source

C # Exception Handling summary

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.