Suppress first chance exceptions

泄露秘密 提交于 2019-11-28 21:14:02

DebuggerNonUserCodeAttribute Class

As of .NET 2.0, if you mark an method with the [DebuggerNonUserCode] attribute, the debugger will skip first chance exceptions in it.

Quote from MSDN link (emphasis added is mine):

members that are not part of the code specifically created by the user can complicate the debugging experience. This attribute suppresses the display of these adjunct types and members in the debugger window and automatically steps through, rather than into, designer provided code.

There is no runtime behaviour apart from debugging, associated with this attribute.

However if you have just one method with certain lines intended for inclusion in Visual Studio's first chance exception handling mechanism, and other lines to be excluded, there's likely not a solution at this level of granularity. You can always refactor a large method into multiple methods and use the attribute on select ones.


Additional Info...

Example usage from this article

using System.Diagnostics;
using XL = Microsoft.Office.Interop.Excel;

public static class WorkbookExtensions
{
    [DebuggerNonUserCode]
    public static bool TryGetWorksheet(this XL.Workbook wb, string worksheetName, out XL.Worksheet retrievedWorksheet)
    {
        bool exists = false;
        retrievedWorksheet = null;

        try
        {
            retrievedWorksheet = GetWorksheet(wb, worksheetName);
            exists = retrievedWorksheet != null;
        }
        catch(COMException)
        {
            exists = false;
        }

        return exists;
    }

    [DebuggerNonUserCode]
    public static XL.Worksheet GetWorksheet(this XL.Workbook wb, string worksheetName)
    {
        return wb.Worksheets.get_Item(worksheetName) as XL.Worksheet;
    }
}

The article shows related VS project options that might be useful.

This is happening because you are mis-using exceptions. Getting 50 before you get to the "interesting code" is not a good sign. There is no way in Visual Studio to skip them in some code, because it's not designed to encourage what you are doing.

That said, what I'd do would be to turn off catching first-chance exceptions in the debugger, explicitly try/catch the exception you do want to catch, and put in a Debugger.Break() when you've caught it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!