Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Exception, add data, and rethrow it

Tags:

c#

exception

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.

like image 900
Sebastian Negraszus Avatar asked Feb 27 '12 15:02

Sebastian Negraszus


People also ask

Is it possible to rethrow a caught exception?

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.

What does it mean to Rethrow an exception?

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.

Does catch block Rethrow an exception in Java?

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.

What keyword is used to Rethrow an exception C#?

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.


1 Answers

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; } 
like image 79
Menelaos Vergis Avatar answered Oct 08 '22 02:10

Menelaos Vergis