New Mechanism for exception handling in. Net 4.0

Source: Internet
Author: User

A friend asked me why I was. NetCannot capture (Catch) And cannot be caught in the debugger. After studying it, yes. Net 4.0The new exception handling mechanism.

 

In. Net 4.0After,CLRSome exceptions (bothSehException), identify these exceptions as destructive exceptions (Corrupted state exception). For these exceptions,CLROfCatchBlocks do not capture these exceptions, even if you useCode:

Try
{
Testmethod ();
}
Catch ( Exception E)
{
Console . Writeline ( "Catching exception: {0 }" , E );
}

There is no way to catch these exceptions. The reason for this design lies in Msdn OfArticle Handling failed upted state exceptions . That is, some plug-ins supportProgramFor example Visual Studio Or SQL Server They support calling plug-ins written by managed code, but they own a lot of code that is not managed C ++ . Because plug-ins often call unmanaged API For a long time, the code of these plug-ins does not know how to handle unmanaged API Thrown SehException. In 4.0 Previously, because Seh The exception is converted to a common . Net Exceptions are the same, so that programmers only need to use Catch (exception E) To capture all exceptions. To solve this problem Seh Exceptions are usually not thrown by managed code, and managed code is not known at all. Seh The cause of the exception is simple. Catch (exception E) Processing puts the entire program in a very unstable state, making the previously ignored problem appear in a more serious way later. - For example, save damaged data. In this way, it looks like Catch (exception E) The method to handle all exceptions is simple, but in fact it takes more effort for programmers or users to analyze the problem after it is delayed.

 

Therefore4.0Later, mostSeh(I suspect it is all) exceptions are identified as destructive exceptions. NetBy defaultCLRThey are not captured, but are processed by the operating system-that is, the program is closed and an error dialog box is opened to notify users. To ensure compatibility4.0Previously compiled programs, such2.0,3.0And3.5The compiled program still adopts the old policy-that is. NetCaptured at the same time. NetException andSehException. In4.0The program compiled below will use the new policy, which is also a problem that my friends encountered at the beginning of the article. You can. Net 4.0Compile the following program to experience this new change:

Program. CS:

 Using System;
Using System. runtime. interopservices;

Namespace Leleapplication1
{
Class Program
{
[ Dllimport ( "Ref. dll" )]
Private Extern Static Void Testmethod ();

Static Void Main ( String [] ARGs)
{
Try
{
Testmethod ();
}
Catch ( Exception E)
{
Console . Writeline ( "Catching exception: {0 }" , E );
}
}
}
}

 

 

Ref. cpp:

 # Include  "Stdafx. H"

Extern "C" _ Declspec(Dllexport)VoidTestmethod ()
{
Int* P = NULL;

// Will cause . Net Throw Accessviolation Exception
* P = 10;
}

 

In the above Code,Program. CSUseP/invokeTechnology calledRef. dllFileTestmethod,TestmethodTry to assign a value to a null pointer, resulting inAccessviolationException. If you are2.0Compile the following codeProgram. CSAnd run the following command:AccessviolationException will beCatch (exception E)Captured, and if you are4.0If you compile and execute the following code, you will find thatCatch (exception E)This exception cannot be caught.

 

However, not everyone wants this new exception mechanism. If your program is4.0Compile and run the following code, and you want. NetCaptured in the programSehIf an exception occurs, you can try the following two solutions:

1.In. ConfigFile, enableLegacypolicuptedstateexceptionspolicyThis attribute is simplified. ConfigThe file is similar to the following file:

 

App. config:

<? XML Version = "1.0"?>
<Configuration>
< Startup >
< Supportedruntime Version = "V4.0"SKU=". Netframework, version = v4.0"/>
</ Startup >
<Runtime>
<Legacypolicuptedstateexceptionspolicy Enabled="True"/>
</Runtime>
</Configuration>

 

This setting tellsCLR 4.0, Entire. NetPrograms must use the old exception capture mechanism.

 

2.AddHandleprocesscorruptedstateexceptionsAttribute. This attribute only controls one function and has no effect on other functions of the managed program. For example:

  [ handleprocesscorruptedstateexceptions ] 
static void main ( string [] ARGs)
{< br> try
{< br> testmethod ();
}< br> catch ( exception E)
{< br> console . writeline ( "catching exception: {0}" , e );
}< BR >}

 

You can also download the sample code and give it a try (requiredVs 2010Can be compiled ):

/Files/killmyday/csesample.zip

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.