Reputation: 52523
I've looked at a few other try catch finally
questions on here but I'm not sure that this one has been answered. Does it smell bad to do something like:
Exception? ex = null;
try { //something }
catch (Exception e) { ex = e ;}
finally {
DoSomething();
}
... //more code
//end of method
if (ex !=null) { throw ex; }
Basically, I'm trying to ensure that certain code (outside of the try/catch/finally) is run and that an exception is thrown if one happens, but not until after said code runs. I can't put all the code in the finally
block because it's outside of some conditionals.
If this does, in fact, smell bad (I suspect it does), how would one achieve this?
Upvotes: 1
Views: 659
Reputation: 31394
That is definitely a code smell. Re-throwing the exception at the end of the method will overwrite the call stack of the exception so it will appear that all exceptions occurred at the end of the method instead of where they really occurred.
If you can't place the extra code in the existing finally, you create nested try..finally blocks:
try {
try { //something }
finally {
DoSomething();
}
... //more code
}
finally {
// cleanup code
}
Note From OP: see this code for what this answer's author led me to correctly derive.
Upvotes: 6
Reputation: 39296
Since you want to run "more code" even in the event of an exception, why not put "more code" in the finally? That's essentially what the finally is for - it's guarenteed to execute even if an exception happens
so:
try {
// something
} catch (Exception e) {
***// more code here***
DoSomething();
throw;
}
Storing ex and throw ex; will swallow inner expections. You want throw; to ensure nothing in the stack is swallowed.
Upvotes: 0