I have the following code:
try { OnInitialize(); } catch (PageObjectLifecycleException exception) { exception.OldLifecycleState = CurrentLifecycleState; exception.RequestedLifecycleState = LifecycleState.Initialized; throw exception; }
I catch an exception, add some more data to it, and rethrow it. Resharper warns me (correctly) that a rethrow is possibly intended and suggests changing it to:
throw;
But I'm wondering: Will this correctly rethrow the modified exception or the unmodified original one?
Edit: In response to the "Try it and see" comments: I am new to C#, comming from C++. In C++ you often find undefined behaviour in corner cases like this and I am interested in whether what I want is really how it officially works.
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.
Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.
In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e , is type Exception , and the catch block rethrows the exception parameter e , you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.
Re-throwing an Exception The catch block simply throws that exception using only throw keyword (not throw e). This will be handled in catch block in Method1() where it again re-throw the same exception and finally it is being handled in the Main() method.
You can add the extra information into data and re-throw the exception with throw
so it maintains its original form and the callstack
try { ... } catch (PageObjectLifecycleException exception) { exception.Data.Add("additional data", "the additional data"); throw; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With