开发者

Lambdas and Exception handling

开发者 https://www.devze.com 2022-12-08 09:24 出处:网络
I have something like the following: public class FooWrapper { public Action Foo { get; set; } public void Execute()

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?


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?


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.

0

精彩评论

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