Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't catch exception thrown during lazy initialization (C# .NET)

Tags:

c#

.net

I am trying to initialize an expensive object, through .NET's Lazy class, that can fail due to an exception. The instance of the lazy class is cached because it is possible that on a subsequent attempt initialization can succeed. I am thus creating the instance as follows:

Lazy<someObject> lazyValue =
    new Lazy<someObject>(() => { expensive initialization; }, 
        System.Threading.LazyThreadSafetyMode.PublicationOnly);

According to .NET's documentation with PublicationOnly the exception will not be cached and thus one can attempt to reinitialize the value. I ran into the issue that the exception cannot be caught. Now it is fairly simple to write my own lazy class but I would like to find out if I am using .NET's Lazy class incorrectly or is their a bug?

The following (simplified) code will reproduce the problem:

private static void DoesntWork()
{
    int i = 0;

    Lazy<string> lazyValue = new Lazy<string>(() =>
    {
        if (i < 2)
        {
            throw new Exception("catch me " + i);
        }

        return "Initialized";
    }, System.Threading.LazyThreadSafetyMode.PublicationOnly);

    for (; i < 3; i++)
    {
        try
        {
            Console.WriteLine(lazyValue.Value);
        }
        catch (Exception exc) // I do not catch the exception!
        {
            Console.WriteLine(exc.Message);
        }
    }
}
like image 910
Rehan Avatar asked May 05 '11 13:05

Rehan


1 Answers

Well, it looks like it should work. If you're saying that it's throwing the exception but not catching it, then... by any chance, are you running in Visual Studio, and have ArgumentException checked in the Debug > Exceptions menu for telling it to always break there?

like image 88
Tesserex Avatar answered Sep 18 '22 04:09

Tesserex