C # Exception Handling and experiences

Source: Internet
Author: User
Tags integer division

Exceptions in C sharp are used to handle system-level and application-level error states. It is a structured and unified type-safe processing mechanism. C #'s exception mechanism is very similar to c ++'s exception handling mechanism, but there are still some important differences:

1. in C #, all exceptions must be represented by an instance of the class type derived from System. Exception. In C ++, any value of any type can be used to indicate an exception.

2. in C #, The finally block can be used to compile the termination code that will be executed under normal execution and exceptions. In C ++, it is difficult to write such code without repeating the code.

3. in C #, system-level exceptions, such as overflow, Division by zero, and null, all correspond to the exception classes that match them, and is in the same status as application-level errors.

1.1 causes of exceptions

Exceptions can be thrown in two different ways.

· The throw Statement (section 8.9.5) is used to immediately and unconditionally raise an exception. The control will never reach the statement followed by throw.

· Some exceptions may occur during the execution of C # statements and expressions, so that some operations cannot be completed normally. In this case, an exception is thrown. For example, in integer division (section 7.8.2 of integer division), if the denominator is zero, System. DivideByZeroException is thrown. For a list of exceptions that may be thrown in this way, see section 16.4.

1.2System. ExceptionClass

The System. Exception class is the base type of all exceptions. This class has some noteworthy attributes shared by all exceptions:

· Message is a read-only attribute of the string type. It contains a description of the cause of the exception (easy to read manually ).

· InnerException is a read-only attribute of the Exception type. If its value is not null, it references the exception that causes the current exception, that is, the current exception is thrown in the catch block that handles the InnerException. Otherwise, its value is null, indicating that the exception is not caused by another exception. The number of abnormal objects linked together in this way can be arbitrary.

The values of these attributes can be specified when the System. Exception instance constructor is called.

1.3Exception 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.

If no matching catch clause is found, one of the following two situations occurs:

· If a search for a matched catch clause reaches a static Constructor (section 10.12 of limit) or an initial value of a static field, the System is triggered at the location where the static constructor is called. typeInitializationException. The internal exception of the System. TypeInitializationException will include the initial exception.

· If the search for a matched catch clause reaches the code of the current thread that was initially started, the execution of this thread will be terminated. The impact of such termination should be defined by implementation.

It is worth noting that exceptions occur during the execution of destructor. If an exception occurs during the execution of the Destructor and the exception is not captured, the execution of the Destructor is terminated, and call the destructor of its base class (if any ). If there is no base class (such as in the case of object type), or if there is no base class destructor, this exception will be ignored.

1.1 Common exceptions
The following exceptions are caused by some C # operations.

1 System.ArrayTypeMismatchException

When an array is stored, this exception is thrown if the storage fails because the actual type of the stored element is incompatible with the actual type of the array.

1 System.DivideByZeroException

This parameter is triggered when a zero-division integer is used.

1 System.IndexOutOfRangeException

This is triggered when you try to use a subscript index array that is less than zero or exceeds the limit of the array.

1 System.InvalidCastException

This exception is thrown when the explicit conversion from the base type or interface to the derived type fails at runtime.

1 System.NullReferenceException

This exception is thrown if null reference is used when a reference object is required.

1 System.OutOfMemoryException

Triggered when the attempt to allocate memory (via new) fails.

1 System.OverflowException

This is triggered when the arithmetic operation in the checked context overflows.

1 System.StackOverflowException

This exception is thrown when the execution stack is exhausted because it saves too many pending method calls. This usually indicates that there is a very deep or infinite recursion.

1 System.TypeInitializationException

This is triggered when a static constructor raises an exception and no catch clause can be captured.

Okay's content above is a summary of the exception handling in the c # language specification. Below we will summarize some of the problems we are new to. Please add them. Thank you!
1. are using commands or assembly references missing?
This is a frequently encountered problem in my recent explorations. Although I have already added references, I will always remind you that I have summarized two common solutions:
1. Modify: Right-click the class file-properties-generate operation-change "content" to "compile", and then generate the file again to solve the problem.
2. In another case, multiple class libraries exist in the project. when a project is generated, the system prompts that the type or namespace name "XXXX" is not found (is the using instruction or assembly reference missing ?) Find the "Reference" folder in the corresponding class library, add the corresponding dll file in it, and generate such a library separately. If the prompt is still displayed, check whether the dll files generated by referencing other class libraries exist. If yes, make sure that the class libraries that generate the dll files can be generated normally, and so on, finally, the entire project is generated.
Ii. try, catch, finally
I understand it in this way. First, execute the statements in try. If the statements in try throw an error, they will be caught by catch, therefore, the execution of the statements in the try will be interrupted and the statements in the catch will be executed. If all the statements in the try are executed and no error is thrown, then the statements in the catch will not be executed. Finally, no matter whether the try runs smoothly or whether the try throws an error or is caught by the catch statement and executed by the catch statement, the statements in finally must be executed. But what are the disadvantages ~

 

Here is an optimal troubleshooting method on msdn, which may be helpful.

Http://msdn.microsoft.com/zh-cn/library/seyhszts.aspx

Related Article

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.