有选择地忽略C#代码中抛出的exception

我在C#代码中有一个函数,其中定期抛出NullReferenceException(预期的行为),但是被捕获。 有没有办法告诉Visual Studio调试器不要在我的代码的这个特定部分中断这个exception?

编辑我需要在我的代码中的其他地方打破这个exception,但不是在同一个函数中。

如果我理解正确,你要做的是调试一些NullReferenceException但想在调试时暂时忽略其他人,你可以通过使用DebuggerNonUserCode属性标记希望调试器忽略的函数来做到这一点。

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

请注意 ,这仅在所述方法中捕获exception时才有效。 只是如果你将调试器设置为总是在NullReferenceExceptionexception中断,它们就不会导致调试器中断。 并且这只适用于方法,而不是方法内的任意代码段。

假设exception没有冒泡到调用者,可以使用DebuggerHiddenAttribute实现。

从言论来看

Visual Studio 2005调试器不会在标有此属性的方法中停止,并且不允许在方法中设置断点。

  [DebuggerHidden] private static void M() { try { throw new NullReferenceException(); } catch (Exception) { //log or do something useful so as not to swallow. } } 

您可以这样做,但它确实会影响解决方案中的所有exception。

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