If you’re opening connections usually what you do is a try-catch-finally
try {
doSomething();
} catch(Exception e) {
// handle the exception
} finally {
close();
}
In my scenario I’ve two catch and two different closing: close() in the normal case and closeStrange() if a StrangeException is thrown.
I came up with something like this:
try {
doSomething();
} catch(StrangeException e) {
closeStrange();
throw new MyExc(e);
} catch(Exception e) {
close();
throw new MyExc(e);
}
close();
I would like to know if handle this situation in this way it’s safe.
EDIT:
Probably it wasn’t clear: I want just one of the closing to be called.
closeStrange() if the StrangeException is thrown,
close() if another Exception or none is thrown.
No, the way you’re handling this at the moment isn’t safe:
finallyblock, so any non-Exception that’s thrown will leave you without closing the connectionYou probably want:
Note that if
closeStrangely()throws an exception, this will attempt to close it “normally”. If you don’t want that behaviour, setclosedStrangelyto true before callingcloseStrangely.EDIT: Even if you want to throw a custom exception in some cases, you almost certainly shouldn’t be catching
Exception.