Mike
Mike

Reputation: 1425

Lambdas and Exception handling

I have something like the following:

public class FooWrapper
{
    public Action Foo { get; set; }

    public void Execute()
    {
        try
        {
            Foo.Invoke();
        }
        catch (Exception exception)
        {
                //exception is null
            //do something interesting with the exception 
        }
    }
}

When I run my unit test with something like the following:

new FooWrapper() { Foo = () => { throw new Exception("test"); } };

The exception is thrown as expected but and the catch steps through but "exception" is null. How do I get to the exception thrown by an .Invoke() to properly handle it?

Upvotes: 1

Views: 243

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064004

It only ever appears null if you have a breakpoint outside the exception line; inside, it should be non-null. I've just tested it, and got an Exception with Message="test", as expected.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755357

This sounds like a bug in the code inside your catch block. The exception value in a catch block as defined by your sample cannot ever be null. There must be a non-null exception value for that code to execute.

Can you post the contents of your catch block?

Upvotes: 2

Related Questions