Selectively ignore thrown exceptions in C# code

前端 未结 3 1448
时光取名叫无心
时光取名叫无心 2021-01-06 01:32

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 n

相关标签:
3条回答
  • 2021-01-06 01:44

    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..

    0 讨论(0)
  • 2021-01-06 01:47

    You can do this, but it does effect all exceptions in the solution.

    Debug -> Exceptions -> Find... "Null Ref", de-tick Thrown.

    0 讨论(0)
  • 2021-01-06 01:53

    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.
            }            
        }
    
    0 讨论(0)
提交回复
热议问题