Visual Studio 2019 breaks on already handled exception (C#)

Viewed 915

I have some code in a try-catch block, which may throw exceptions.

The exception is handled in the catch block.

The code works under VS 2017. However, switched to VS2019, the debugger won't continue (see screenshot)

How can I tell the debugger no to break at already handled exceptions ?

enter image description here

[Edit]

In this particular case, the exception can easily be avoided with more careful code, or disabled by unchecking the "Break when this exception type is thrown".

However it is NOT my question.

My question is :

Why VS 2019 breaks at alrady handled exceptions ?

How can I tell it no to do so ?

3 Answers

[EDIT: This question is not regarding correct handling, but breaking behaviours. The example contained is of course NOT recommended handling]

As per Mattias Larsson's answer, a number of Exceptions, by default, will always break execution regardless of if they are handled or not. A System.NullReferenceException is one of them. To prevent this, you can uncheck the box break when this exception type is thrown. Doing so will result in the following behavior:

breaking behaviour

As you previously commented, when not handled, you wish the debugger to continue to break on a System.NullReferenceException; this is the standard behavior since such an exception is critical i.e. not recoverable (perhaps there's a better term?).

There are a number of exceptions that (by default) breaks the execution even if you have a 'catch all'. System.NullReferenceException is one of them.

However, as you can see in the popup in your screenshot you have the option to turn this specific exception "off". It's currently checked: "Break when this exception type is thrown".

Uncheck this box and try again!

(You can adjust the exception settings further in this menu option: Debug / Windows / Exception Settings.)

There's already a lot being said on why this would be 'bad practice'.

That being said, there is debuggerStepThrough

https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerstepthroughattribute?view=netcore-3.1

Make sure to read the docs to understand the implications - for ex. that you need JMC to be enabled.

Also when making these dirty exception checks that you do - please make them as specific as possible, to avoid suprises;

try
{
   var x = MyFunc();

   // We do a check here that will throw an exception 
   var y = ThisFuncWillThrowNullRef(x);
}
catch(exception)
{
    // ALL exceptions are swallowed
    // What if MyFunc() throws an exception instead of the second function? what do we do then?
}


edit; in the app i work on, even if we 'swallow' exceptions like you're doing now, we explicitly and verbosely log the the exception. Always. Exceptions are easier to fix than not knowing what's going on and as your app gets larger there will be more and more happening under the hood.

Related