Erwin Mayer Erwin Mayer - 2 months ago 30
C# Question

Visual Studio 2015 unexpectedly breaking on handled exceptions

An image being worth a lot of words, how is the following possible:

Visual Studio 2015 breaking while it should not

As can be seen, Visual Studio 2015 (latest version) breaks while

Common Language Runtime Exceptions
under
Exception Settings
is unchecked,
Enable Just My Code
under
Tools > Options > Debugging
is checked, and the exception is clearly handled (within a try/catch block).

The line failing and causing the break is a call to an external API (which is somewhat buggy, hence the try/catch block).

Am I missing something that would justify the break or is this a bug? I thought this other question would provide some insight but it unfortunately does not help here (the exception is handled so we should not need to enable the additional
Continue When Unhandled in User Code
option.

Answer

There is a special case for this exception, which I am guessing applies here. From the docs:

AccessViolationException and try/catch blocks

Starting with the .NET Framework 4, AccessViolationException exceptions thrown by the common language runtime are not handled by the catch statement in a structured exception handler if the exception occurs outside of the memory reserved by the common language runtime. To handle such an AccessViolationException exception, you should apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method in which the exception is thrown. This change does not affect AccessViolationException exceptions thrown by user code, which can continue to be caught by a catch statement. For code written for previous versions of the .NET Framework that you want to recompile and run without modification on the .NET Framework 4, you can add the element to your app's configuration file. Note that you can also receive notification of the exceptions if you have defined a handler for the AppDomain.FirstChanceException or AppDomain.UnhandledException event.

As the docs say, the solution is to add the HandleProcessCorruptedStateExceptionsAttribute to the Start() method. If not possible (e.g., this is supplied via a library), I'm guessing you can add a method that wraps the call and add the attribute to that wrapping method.

Comments