Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make [DebuggerNonUserCode] hide an exception from the debugger in simple test case?

Setup:

1) MSVS 2015, Option -> Debugger -> "Just My Code" is checked.

2) This sample code placed within some class and called during startup:

    static bool TestIgnoreException()
    {
        Exception ex;
        return TrySomething(out ex);
    }

    [DebuggerNonUserCode] // Prevent exceptions from stopping the debugger within this method. 
    static bool TrySomething(out Exception exOut)
    {
        try
        {
            if (Environment. MachineName.Length != -1)
                throw new Exception("ThrewIt.");

            exOut = null;
            return true;
        }
        catch (Exception ex)
        {
            exOut = ex;
            return false;
        }
    }

3) Launch Debugger

Expected result is that TestIgnoreException() runs silently and returns false.

Actual result is the debugger stops in TestIgnoreException() even though there should be no exception being processed at that scope.

enter image description here

4) Also re-tried using [DebuggerHidden] instead, same results.

Motivation:

The motivation is for cases where some API that is out of your control does not provide a "Try" method and instead only indicates failure by using exceptions.

One of numerous such examples is .NET TcpClient.Connect(host, port). Say a program always tests some connections during startup, the debugger should not stop on this particular section of code each time.

Using the standard "break when thrown" exceptions checkboxes is is not good because it works globally by type. It cannot be configured to work locally. Also other developers who check out the code should automatically skip the exception as well.

like image 586
crokusek Avatar asked Sep 08 '16 04:09

crokusek


1 Answers

Mystery solved. It is indeed a known issue that is new to MSVS 2015 because of added exception handling optimizations.

https://blogs.msdn.microsoft.com/visualstudioalm/2016/02/12/using-the-debuggernonusercode-attribute-in-visual-studio-2015/#

There is a workaround posted on that link to disable the optimizations and enable the old behavior. Hopefully they will eventually be able to revive the support for this including the optimizations.

reg add HKCU\Software\Microsoft\VisualStudio\14.0_Config\Debugger\Engine /v AlwaysEnableExceptionCallbacksOutsideMyCode /t REG_DWORD /d 1

Related question:

Don't stop debugger at THAT exception when it's thrown and caught

like image 129
crokusek Avatar answered Oct 06 '22 19:10

crokusek