Chapter VII. net Programming pioneer C # Exception Handling

Source: Internet
Author: User
Tags finally block

Chapter 7 Exception Handling
Common Language Runtime (CLR) has a major advantage in that exception handling is cross-language standardized. An exception thrown in C # can be handled in Visual Basic. There are no HRESULTs or ISupportErrorInfo interfaces.
Despite the wide coverage of cross-language Exception Handling, this chapter focuses entirely on C # exception handling. To change the overflow processing behavior of the compiler, the interesting thing begins: You have handled the exception. You need to add more methods and then cause the exceptions you have created. </P> <P> 7.1 checked and unchecked statements
When you perform an operation, the calculation result may be out of the valid range of the Data Type of the result variable. This situation is called overflow. Depending on different programming languages, you will be notified in some way-or you will not be notified at all. (Do C ++ programmers sound familiar ?)
So, how does C # handle overflow? To find out its default behavior, see the factorial example I mentioned earlier in this book. (For convenience, the previous example is given again in listing 7.1) </P> <P> List 7.1 calculates the factorial of a number </P> <P> 1: using System;
2:
3: class Factorial
4 :{
5: public static void Main (string [] args)
6 :{
7: long nFactorial = 1;
8: long nComputeTo = Int64.Parse (args [0]);
9:
10: long nCurDig = 1;
11: for (nCurDig = 1; nCurDig <= nComputeTo; nCurDig ++)
12: nFactorial * = nCurDig;
13:
14: Console. WriteLine ("{0 }! Is {1} ", nComputeTo, nFactorial );
15 :}
16 :}</P> <P> when you execute a program using a command line like this
Factorial 2000 </P> <P> the result is 0 and nothing happens. Therefore, imagine C # To handle overflow silently without explicitly warning you that it is safe.
You can change this behavior by allowing overflow verification at the statement level for the entire application (switched by the compiler. The following two sections provide a solution.
7.1.1 configure the compiler for overflow Verification
If you want to control overflow verification for the entire application, the C # compiler setting is exactly what you are looking. By default, overflow verification is disabled. To explicitly require it, run the following compiler command:
Csc factorial. cs/checked + </P> <P> now, when you use the 2000 parameter to execute an application, CLR notifies you of an overflow exception (see Figure 7.1 ). </P> <P> FIGURE 7.1 allows overflow exceptions. The factorial code generates an exception. </P> <P> press OK to exit the dialog box. Exception information is displayed:
Exception occurred: System. OverflowException
At Factorial. Main (System. String []) </P> <P> now you know that the overflow condition causes a System. OverflowException exception. In the next section, how do we capture and handle exceptions after we complete the syntax validation?
7.1.2 syntax overflow check
If you do not want to allow overflow verification for the entire application and only allow verification for some code segments, you may be comfortable. In this case, you may use the verification statement as shown in listing 7.2. </P> <P> List 7.2 overflow verification in factorial calculation </P> <P> 1: using System;
2:
3: class Factorial
4 :{
5: public static void Main (string [] args)
6 :{
7: long nFactorial = 1;
8: long nComputeTo = Int64.Parse (args [0]);
9:
10: long nCurDig = 1;
11:
12: for (nCurDig = 1; nCurDig <= nComputeTo; nCurDig ++)
13: checked {nFactorial * = nCurDig ;}
14:
15: Console. WriteLine ("{0 }! Is {1} ", nComputeTo, nFactorial );
16 :}
17 :}</P> <P> even if you use the flag checked-to compile the code, overflow verification will still check the multiplication in Row 3. The error message is consistent. </P> <P> the statement that shows the opposite behavior is unchecked ). Even if overflow verification is allowed (the checked + flag is added to the compiler), the code enclosed by the unchecked statement will not cause an overflow exception: </P> <P> unchecked
{
NFactorial * = nCurDig;
} </P> <P> 7.2 Exception Handling statement
Since you know how to generate an exception (you will find more methods, believe me), there are still problems with how to handle it. If you are a C ++ WIN32 programmer, you must be familiar with SEH (Structure Exception Handling ). You will find comfort in that the commands in C # are almost the same and they operate in a similar way. </P> <P> The following three sections introduce C # s exception-handling statements:
The following three sections describe the C # Exception Handling statement: </P> <P>. Catch exceptions with try-catch
. Use try-finally to clear exceptions
. Use try-catch-finally to handle all exceptions </P> <P> 7.2.1 use try and catch to catch exceptions
You will certainly be very interested in one thing-do not prompt the user for the annoying exception message, so that your application can continue to execute. To do this, you must capture (handle) the exception.
In this way, try and catch are used. Try contains statements that may generate exceptions, while catch processes an exception. If an exception exists. Listing 7.3 uses try and catch as OverflowException to handle exceptions. </P> <P> listing 7.3 captures an OverflowException exception caused by Factorial Calculation </P> <P> 1: using System;
2:
3: class Factorial
4 :{
5: public static void Main (string [] args)
6 :{
7: long nFactorial = 1, nCurDig = 1;
8: long nComputeTo = Int64.Parse (args [0]);
9:
10: try
11 :{
12: checked
13 :{
14: for (; nCurDig <= nComputeTo; nCurDig ++)
15: nFactorial * = nCurDig;
16 :}
17 :}
18: catch (OverflowException oe)
19 :{
20: Console. WriteLine ("Computing {0} caused an overflow exception", nComputeTo );
21: return;
22 :}
23:
24: Console. WriteLine ("{0 }! Is {1} ", nComputeTo, nFactorial );
25 :}
26 :}</P> <P> for clarity, I have extended some code segments and ensured that exceptions are generated by the checked statement, even when you forget the compiler settings.
As you can see, exception handling is not troublesome. All you have to do is: Include the code that is prone to exceptions in the try statement, and capture the exception. This exception is of the OverflowException type in this example. No matter when an exception is thrown, the code in the catch segment must be properly processed.
If you do not know which exception will be expected, but want to be in a safe state, simply ignore the exception type. </P> <P> try
{
...
}
Catch
{
...
} </P> <P> however, in this way, you cannot access the exception object, which contains important error information. The General Exception Handling Code is as follows: </P> <P> try
{
...
}
Catch (System. Exception e)
{
...
} </P> <P> Note: you cannot use the ref or out modifier to pass an e object to a method or assign a different value to it. </P> <P> 7.2.2 use try and finally to clear exceptions
If you are more concerned with clearing, rather than error handling, try and finally will enjoy it. It not only suppresses error messages, but also executes all code contained in the finally block after an exception is thrown.
Although the program is not terminated normally, you can obtain a message for the user, as shown in listing 7.4. </P> <P> List 7.4 Exception Handling in finally statements </P> <P> 1: using System;
2:
3: class Factorial
4 :{
5: public static void Main (string [] args)
6 :{
7: long nFactorial = 1, nCurDig = 1;
8: long nComputeTo = Int64.Parse (args [0]);
9: bool bAllFine = false;
10:
11: try
12 :{
13: checked
14 :{
15: for (; nCurDig <= nComputeTo; nCurDig ++)
16: nFactorial * = nCurDig;
17 :}
18: bAllFine = true;
19 :}
20: finally
21 :{
22: if (! BAllFine)
23: Console. WriteLine ("Computing {0} caused an overflow exception", nComputeTo );
24: else
25: Console. WriteLine ("{0 }! Is {1} ", nComputeTo, nFactorial );
26 :}
27 :}
28 :}</P> <P> by detecting this code, you may guess that finally will be executed even if no exception is thrown. This is true-the code in finally will always be executed, regardless of whether the exception conditions exist. To illustrate how to provide meaningful information to users in two cases, I introduced the new variable bAllFine. BAllFine tells finally whether it is called because of an exception or just because of the successful completion of computing.
As a programmer accustomed to SEH, you may wonder if there is a statement equivalent to the _ leave Statement, which is useful in C ++. If you do not know, the _ leave statement in C ++ is used to terminate the Execution Code in the try Language Segment in advance and immediately jump to the finally Language Segment.
Bad message. C # does not have the _ leave statement. However, the Code in listing 7.5 demonstrates a solution that you can implement. </P> <P> List 7.5 jump from try statement to finally statement </P> <P> 1: using System;
2:
3: class JumpTest
4 :{
5: public static void Main ()
6 :{
7: try
8 :{
9: Console. WriteLine ("try ");
10: goto _ leave;
11 :}
12: finally
13 :{
14: Console. WriteLine ("finally ");
15 :}
16:
17: _ leave:
18: Console. WriteLine ("_ leave ");
19 :}
20 :}</P> <P>
When the application is running, the output result is </P> <P> try
Finally
_ Leave </P> <P> A goto statement cannot exit a finally segment. Even if the goto statement is placed in the try statement segment, the return will be immediately controlled to the finally segment. Therefore, goto only leaves the try CIDR Block and jumps to the finally CIDR block. The _ leave tag can be reached only after the finally code is completed. In this way, you can imitate the _ leave statement used in SEH.
By the way, you may suspect that the goto statement is ignored because it is the last statement in the try statement and the control is automatically transferred to finally. To prove this is not the case, try to put the goto statement into the Console. WriteLine Method

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.