Several misunderstandings about. Net Exception Handling

Source: Internet
Author: User
Tags pop value

Author: Truly
Date: 2007.8.5

I wanted to write this article a long time ago.ArticleBecause many people use it.. net has been familiar with exception handling for many years. There are many misunderstandings. This article will explain three common misunderstandings: whether catch is used correctly, the other two problems are the performance loss of try/catch.

Some people think that the followingCodeIs a catch error usage:

Catch (Exception E)
{
Throw E;
}

This is not an error, but we should avoid this code. It should be noted that this piece of code has a typical function of changing the location where an exception occurs, that is, it can be processed in a uniform location for a certain exception. First look at the following code:

Public   Int Getallcount2 ()
{
Try
{
Opendb ();
Int I =   1 ;
Return I;
}
Catch (Sqlexception sex)
{
Throw Sex;
}
Catch (Exception ex)
{
Throw Ex;
}
}
Public   Int Getallcount ()
{
Opendb (); // This may also be a Microsoft Enterprise Library.
Int I =   1 ;
Return I;
}

Private VoidOpendb ()
{
Conn. open ();
}

Suppose we have a public method called opendb (), and many methods call it. When the database fails to be opened, the exception for calling the getallcount method will be located in conn. open. If getallcount2 is called, the exception is located at the throw sex location, and the stack information is different. You can quickly locate the location of the method to be called, you can also recover some errors here. Especially when writing some underlying class libraries, for example, the framework class library never locates the Exception Code to a method in the framework class library. However, we should try to avoid capturing exceptions without returning them. For example

Catch (){}

This is a typical error, because for the Framework, the system may throwStackoverflowexceptionOrOutofmemoryexcetpionThe above Code hides these exceptions and sometimes causes some serious problems.

For Exception Handling, there are two points of attention in terms of performance

First point, In useTry/catchIf no exception occurs, you can almost ignore the performance loss.

For more information, skip this section. First, let's take a look.Try/catchIl performance. We have two methods, one usingTry/catchAnd the other has not done any processing:

Static   Int Test1 ( Int A, Int B)
{
Try
{
If ( > B)
Return A;
Return B;
}
Catch
{
Return   - 1 ;
}
}

Static IntTest2 (IntA,IntB)
{
If(>B)
ReturnA;
ReturnB;
}

Use the ildasm tool to view the Il Code as follows: (the reason for introducing Il here is that Il is closer to machine assembly, so we can better understand the code execution in Il, skip this section if you are not interested in Il)

. Method private hidebysig static int32 test1 (int32,
Int32 B) Pencil managed
{
// Code size 30 (0x1e)
. Maxstack 2
. Locals Init ([0] int32 CS $1 $0000,
[1] bool CS $4 $0001)
Il_0000: NOP
. Try
{
Il_0001: NOP
Il_0002: ldarg.0
Il_0003: ldarg.1
Il_0004: CGT
Il_0006: LDC. i4.0
Il_0007: CEQ
Il_0009: stloc.1
Il_000a: ldloc.1
Il_000b: brtrue. s il_0011
Il_000d: ldarg.0
Il_000e: stloc.0
Il_000f: Leave. s il_001b
Il_0011: ldarg.1
Il_0012: stloc.0
Il_0013: Leave. s il_001b
} // End. Try
Catch [mscorlib] system. Object
{
Il_0015: Pop
Il_0016: NOP
Il_0017: LDC. i4.m1
Il_0018: stloc.0
Il_0019: Leave. s il_001b
} // End Handler
Il_001b: NOP
Il_001c: ldloc.0
Il_001d: Ret
} // End of method program: test1

Test2

. Method private hidebysig static int32 Test2 (int32,
Int32 B) Pencil managed
{
// Code size 22 (0x16)
. Maxstack 2
. Locals Init ([0] int32 CS $1 $0000,
[1] bool CS $4 $0001)
Il_0000: NOP
Il_0001: ldarg.0
Il_0002: ldarg.1
Il_0003: CGT
Il_0005: LDC. i4.0
Il_0006: CEQ
Il_0008: stloc.1
Il_0009: ldloc.1
Il_000a: brtrue. s il_0010
Il_000c: ldarg.0
Il_000d: stloc.0
Il_000e: Br. s il_0014
Il_0010: ldarg.1
Il_0011: stloc.0
Il_0012: Br. s il_0014
Il_0014: ldloc.0
Il_0015: Ret
} // End of method program: Test2

Here, we only need to focus on several lines highlighted in the red letter. Here we only care about the try block, that is, when no exception occurs, for test1, the Il code has eight more bytes to save the catch processing code, this is almost insignificant for performance and resources.
We can see that when test1 is executedIl_000fOrIl_0013Data is output from the stack and leave. S is used to exit the try block.Il_001bAddress, and then the data into the stack and return.

For Test2, runIl_000eOrIl_0012And then return the data to the stack.

Here is a brief introduction to several key commands

NOPDo noting
Stloc.0Pop value from Stack into local variable 0.
Ldloc.0Load local variable 0 onto stack.
BR. s targetBranch to target, short form
Leave. s targetExit A protected region of code, short form

Next, let's take a look at the actual running status of the code and create a console ConsoleProgram, Add the following code:

Click the icon on the left to show the code.
Static   Void Main ( String [] ARGs)
{
Int Times =   1000000 ; // We enlarge the result by or times.
Long L1, L2, L3, L4, S1, S2;

Console. writeline ("Press any key to continue");
Console. Read ();

for ( int j = 0 ; j 10 ; j + )
{< br> L1 = datetime. now. ticks;

for ( int I = 0 ; I times; I + )
Test2 ( 2 , 4 );

L2=Datetime. Now. ticks;
S1=L2-L1;
Console. writeline ("Time spent:" +S1 );

L3=Datetime. Now. ticks;

For(IntI= 0; I<Times; I++)
Test1 (2,4);

L4 = Datetime. Now. ticks;
S2 = L4 - L3;
Console. writeline ( " Time spent: "   + S2 );
Console. writeline ( " Difference: "   + (S2 - S1) +   " , Rate: "   + ( Float ) (S2 - S1) / S1 / Times );
}
}

Static   Int Test1 ( Int A, Int B)
{
Try
{
For ( Int I =   0 ; I <   100 ; I ++ ); // Simulate long-time operations
If ( > B)
Return A;
Return B;
}
Catch
{
Return   - 1 ;
}
}

Static   Int Test2 ( Int A, Int B)
{
For ( Int I =   0 ; I <   100 ; I ++ ); // Simulate long-time operations
If ( > B)
Return A;
Return B;
}

After running, you can see the code difference, usually within the 0.0001% difference.

Second pointIf an exception occurs, a large amount of system resources and execution time will be used when an exception is thrown or handled. An exception is thrown only to handle actual exceptions, rather than to handle predictable events or flow control. For example, if the method parameter is invalid and the application needs to call the method using a valid parameter, an exception can be thrown. Invalid method parameters indicate exceptions. On the contrary, users occasionally enter invalid data, which is foreseeable. Therefore, if the user input is invalid, do not raise an exception. In this case, provide a Retry Mechanism for users to enter valid input.

We often need to convert a string to an int, such as converting a string like request. querystring ["ID"] to an int. In the Asp.net 1. x era, we often use the following method:

Try
{
Int ID = Int32.parse ( " 123 " );
}
Catch (){}

The consequence is that if a conversion exception occurs, you have to sacrifice a large amount of system resources to handle the exception, even if you have not written any exception processing code.

Of course, you can also write a lot of code to detect and convert strings to replaceTry/catchMethod, and after Asp.net 2.0, the Framework encapsulates this detection conversion process into the int32.tryparse method, and no longer uses the badTry/catch.

One more thing is that the finally code is always running, so let's leave it to everyone. What is the value of a after the code is executed below:

Int =   2 ;
Try
{
Int I = int32.parse ("S ") ;
}
Catch
{
A =   1 ;
Return;
}
Finally
{
A =   3 ;
}

Section: This article mainly corrected three common misunderstandings of exception handling. The writing is in a rush. If there are any omissions, please point out.

References:

Http://msdn2.microsoft.com/zh-cn/library/system.exception (vs.80). aspx
Http://msdn.microsoft.com/library/chs/default.asp? Url =/library/CHS/cpguide/html/cpconexceptionsoverview. asp
Pencil instruction set specification
Applied Microsoft. NET Framework programming

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.