Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectively ignore thrown exceptions in C# code

Tags:

c#

debugging

I have a function in C# code where a NullReferenceException is thrown periodically (expected behavior), but caught. Is there a way I can tell the Visual Studio debugger to not break on this exception for this particular section of my code?

EDIT I need to break on this exception elsewhere in my code, but not in the same function.

like image 260
Bender the Greatest Avatar asked Mar 07 '13 15:03

Bender the Greatest


2 Answers

If I understand correctly and what you're trying to do is debug some NullReferenceException(s) but want to temporarily ignore others while debugging, you might be able to do this by marking functions that you want the debugger to ignore with the DebuggerNonUserCode attribute.

[DebuggerNonUserCode]
private void MyMethod()
{
    // NullReferenceException exceptions caught in this method will
    //  not cause the Debugger to stop here..
}

NOTE that this will only work if the exceptions are caught in said methods. It's just that they won't cause the debugger to break if you have the debugger set to always break on NullReferenceException exceptions. And that this only works on methods, and not arbitrary sections of code inside of a method..

like image 140
Mike Dinescu Avatar answered Sep 30 '22 17:09

Mike Dinescu


Assuming the exception does not bubble up to the caller, this can be achieved with DebuggerHiddenAttribute.

From the remarks

the Visual Studio 2005 debugger does not stop in a method marked with this attribute and does not allow a breakpoint to be set in the method.

    [DebuggerHidden]
    private static void M()
    {
        try
        {
            throw new NullReferenceException();
        }
        catch (Exception)
        {
            //log or do something useful so as not to swallow.
        }            
    }
like image 21
P.Brian.Mackey Avatar answered Sep 30 '22 19:09

P.Brian.Mackey