开发者

Lazy<T> breaks when exception is handled

Maybe I'm missing something but why does visual studio break execution to tell me an exception has occured even though its handled?

Yes, unchecking user-unhandled exception fixes the problem, but why is a handled exception being called a unhandled exception?

Lazy<int> lazyCount = new Lazy<int>(() => { throw new NotImplementedException(); }, System.Threading.LazyThreadSafetyMode.None);
Func<int> valueGenerator = () => { throw new NotImplementedException(); };

try
{
    int value = lazyCount.Value;
}
catch (NotImplementedException e)
{
    Console.WriteLine("Breaks");
}

try
{
    int value = valueGenerator();
}
catch (NotImplementedException e)
{
    Console.WriteLine("Doesn't Breaks");
}

try
{
    throw new NotImplementedException();
}
catch (NotImplementedException e)
{
    开发者_JS百科Console.WriteLine("Doesn't break");
}
Console.ReadLine();


If you're annoyed by the dialog I would recommend disabling the Exception Assistant (I'm not sure what it is assisting).

Tools -> Options -> Debugging

Under this options menu you can disable the Exception Assistant, and control various other debugging features (Just My Code, etc).

As @Michael Kennedy noted you can goto Debug -> Exception... (also Ctrl+Alt+E), click Find and uncheck Thrown for the offending exception.


The debugger is trying to help you and stop early at the source of an exception. You can always just run it outside the debugger by pressing ctrl + F5 rather than F5 to get it running.

For more granularity, check out the Debug->Exceptions menu in Visual Studio.


If you do this:

        Func<int> a = () => { throw new NotImplementedException(); };

        try
        {
            //int value = lazyCount.Value;
            a();
        }
        catch (NotImplementedException e)
        {
        }

You'll notice that it does not break the debugger, even though you're still invoking an anonymous method.

What's happening here is that the LazyThreadSafetyMode.ExecutionAndPublication instructs the Lazy class to cache the Exception so that multiple calls to Value from different threads will throw the same exception. My guess is that they have some additional logic that tells the debugger the exception is unhandled the first time it is thrown, so that you have a chance to inspect the exception in its original context before it is cached and later rethrown. I was going to open up the code in Reflector to see if this is the case, but apparently the free community version of Reflector is no longer free.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜