简体   繁体   中英

Try/Catch/Finally, use exception from Catch in Finally?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM