C # Exception Handling

Source: Internet
Author: User

Using syntax structure
In C #, you can use the using structure to handle certain exceptions. the syntax structure is "using (){}". for example, the following code demonstrates the using structure.
Using (System. IO. FileStream stream
= New System. IO. FileStream ("c: \ a.txt", System. IO. FileMode. Create )){
Stream. WriteByte (byte) 2 );}
In the field code, open the file in brackets after using, create a file stream object, and then output a byte to the file in the code block in the brackets, then there is no other code.
File stream is a very important resource. It must be closed after being opened. Otherwise, the resource will be leaked. In the above Code, you should add the code "stream. close () to Close the file stream. but in fact, the code above is safe and there will be no resource leakage, because the using syntax structure is used.
The above code is equivalent to the following code:
System. IO. FileStream stream
= New System. IO. FileStream ("c: \ a.txt", System. IO. FileMode. Create );
Try {
Stream. WriteByte (byte) 2 );}
Finally {
(System. IDisposable) stream). Dispose ();
}
C # the compiler translates the using structure into a "try {} finally {}" structure and calls the Dispose method of the file stream object in the finally block, this method can close the file stream and release all resources. even if an error occurs in the function code and an exception is thrown, the file stream can still be closed to release the resource.
From this we can see that the using syntax structure has a certain exception processing function. It does not capture exceptions, but can perceive exceptions and perform some processing to reduce the negative impact of exceptions.
The using syntax structure in C # is for System. of the IDisposable interface, System. the Idisposable interface only declares a member "void Dispose ()", which is used to release the important resources occupied by the object. any implemented System. all objects of the IDisposable interface can use the using structure, such as file streams, database connections, and network connections.
Exception Handling Structure
To develop software, you must have sufficient awareness of risks. Recognizing that commercial software runs under Complicated Circumstances will inevitably lead to various risks and errors, which need to be handled. ignoring risks and mistakes, it is dangerous to assume that everything is harmonious.
Actively handle errors
In program development, You can actively handle errors and passively handle errors. When you actively handle errors, you can write code to check before the function is executed, the most common and most effective method is to check whether the method parameters are correct at the beginning of the method body. actively checks the program running speed, and the system is more stable, and the risk is eliminated in the bud, to avoid later errors, so it is the preferred risk processing method.
For example, the following code actively handles errors.
Public int Div (int a, int B)
{
// Check the parameter. If B is 0, an error with 0 division will inevitably occur. Handle the error in advance.
If (B = 0)
{
Return 0;
}
Return a/B;
}
This Code actively checks whether the parameters are correct and stops errors as soon as possible.
Passive Exception Handling
There may be omissions in the method of actively handling errors. in C #, the exception capture mechanism can be used to passively handle errors.
Before explaining an exception, you must first talk about the concept of the call stack of the program. in fact, basically all programming languages have the function of calling stacks. for example, when the program is running, method F1 calls method F2, and F2 instantly calls method F3, method F3 calls method f4at a certain time. There is a call stack of "F1 | F2 | F3 | F4" at this time. as shown in, the code of the program is displayed as a method-based layered structure like an onion, and the lower layer the code is.
The exception in C # is the information about the program module error. if an exception is thrown, the program notifies the system program of the error. This exception is global, starting from the throw point, along the call stack, the higher the layer-by-layer push, the greater the impact. If a layer of code on the call stack can actively capture and handle this exception, the exception disappears and the system can run normally, if no code can capture an exception, the exception will be thrown all the time.. NET Framework.
For example, in a call stack consisting of F1, F2, F3, and F4, if method F4 throws an internal exception, the exception is first thrown to method F3, if F3 does not handle the exception, the exception is thrown to F2 again. If F2 still does not handle the exception, it is still thrown to F1. If F1 does not handle the exception, it is directly thrown. NET framework system.
This is a bit like a petition. The farmers in the village feel that they are not satisfied with the village chief's petition. The village chief does not handle the petition in the county, the county does not handle the petition in the province, and the province does not handle the petition in the central Government, the central government always handles any petition in a simple and crude way. [Yuan Yongfu copyright]
However, it is not good to disturb the center. NET Framework is the center of the. NET application. If the. NET Framework itself handles exceptions not handled by the program, the following program error dialog box will pop up.
For this dialog box, if you click "continue", the program may continue to run, but it may be in an unstable state. Click "exit" to exit the program immediately and unconditionally, this may cause data not to be saved.
Once a system-level error dialog box is displayed, the stability and reliability of the program are very poor. Avoid this situation as much as possible. in this case, you need to add exception handling to some appropriate methods in the call stack to handle exceptions thrown by the underlying method.
Use the "throw" keyword in C # To throw the above. The following Code demonstrates throwing an exception.
Public int F1 (){
ThrownewException ("exception occurred here ");}
In this method, the throw keyword is used to throw an exception. All exceptions in C # are thrown by an underlying method. [Yuan Yongfu copyright ownership]
Note that the method F1 is defined to return an integer value. If the return statement is not compiled in the method body, the throw statement can be used to suppress this rule.
Use the "try {} catch {} finally {}" structure in C # To handle exceptions. The following Code demonstrates how to handle exceptions.
Public void HandleException (int a, int B)
{
Try
{
// Enter the status where exceptions can be captured
F1 ();
}
Catch (Exception ext)
{
// If an exception occurs, capture the exception here and execute this code
System. Windows. Forms. MessageBox. Show (ext. Message );
}
Finally
{
// This code runs regardless of the exception.
Console. WriteLine ("processed ");
}
}
The code block following the keyword "try" generally places functional code of the method. At this time, the system checks whether an exception is thrown. if an exception is thrown, It is captured immediately, then jump to the code block after the keyword "catch" to handle the exception. no matter whether an exception occurs or not, the code block after the keyword "finally" will be executed. This code is generally used for the aftermath of this method, such as releasing important resources applied during work. the Catch Block and finally block are optional. You can also write them as "try {} catch {}" or "try {} finally {}".
For the "try {} catch {}" structure, the program will catch and handle the exception, so that the exception will not be accessed.
For the "try {} finally {}" structure, the program will detect exceptions and perform some processing, but will not capture exceptions, and the exceptions will still be petitioned.
With exception handling, the exception thrown by the underlying method can be handled in a timely manner instead of being pushed all the way.. NET Framework becomes a system-level error. therefore, appropriate exception handling must be added during program development.
Because exceptions are passively handled errors and the execution process consumes a lot of resources, it is always better to actively defend against errors than to passively handle errors. in practice, we can consider using both of them to provide double insurance, so that the program can be reliable and stable.

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.