I’m wondering, is there a way to only execute a block if no exception was thrown?
The best I can come up with is this:
bool exception = false;
try{
// something
}catch(Exception e){
exception = true;
}finally{
if(!exception){
// i can do what i want here
}
}
Is there a better way?
Sure there is: put it at the bottom of the
tryblock.This is not entirely equivalent to your original code in the sense that if “what you want” throws, the exception will be caught locally (this would not happen with your original scheme). This is something you might or might not care about, and there’s a good chance that the different behavior is also the correct one.
If you want to bring the old behavior back, you can also use this variant that doesn’t require a
finallyjust for the sake of writing the “if no exceptions” condition: