1

Let's consider this code :

try
{
    return new ClassA.GetStuff();
}
catch (Exception e)
{
    throw new MyException
        ("message", e)
        {SomeMyExceptionProperty = "something"};
}

When throwing MyException, how the object initialization is done? Like this :

MyException myException = new MyException("message", e);
myException.SomeMyExceptionProperty = "something";
throw myException;

or like this (so the SomeMyExceptionProperty is not initialized) :

MyException myException = new MyException("message", e);
throw myException;
myException.SomeMyExceptionProperty = "something"; //unreachable code

I think that the first behavior is used, like for a return statement, but where is the official documentation about this?

1 Answer 1

7

As ever, the official documentation is the C# specification.

The important part is that this is just a throw statement. It has two parts (in this case):

  • The keyword throw
  • An expression which determines the exception to throw

In this case, the expression includes an object initializer. The whole expression is evaluated before anything is thrown.

From section 8.9.5 of the C# 5 spec:

A throw statement with an expression throws the value produced by evaluating the expression.

Evaluating the expression

new MyException
    ("message", e)
    {SomeMyExceptionProperty = "something"}

... includes assigning the value "something" to the SomeMyExceptionProperty.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.