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?
A finally block always executes, regardless of whether an exception is thrown.
If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs in the try clause, the rest of the clause is skipped. If the exception's type matches the exception named after the except keyword, then the except clause is executed.
If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.
Hi Shola, yes you can use try / catch without a throw. Nevertheless, as try / catch only makes sense if an exception can be thrown, this code would not make much sense.
Sure there is: put it at the bottom of the try
block.
try{ // something // i can do what i want here }catch(Exception e){ // handle exception }
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 finally
just for the sake of writing the "if no exceptions" condition:
var checkpointReached = false; try{ // something checkpointReached = true; // i can do what i want here }catch(Exception e){ if (checkpointReached) throw; // don't handle exceptions after the checkpoint // handle exception }
You don't need the finally clause.
A solution :
bool exception = false; try{ // something }catch(Exception e){ exception = true; } if(!exception){ // u can do what u want here }
Usually you'll simply have a return in your catch clause so that you don't even have to test :
try{ // something }catch(Exception e){ // do things return; } // u can do what u want here
or (depending on the use case and generally less clear, especially if you have more than one exception expected - you don't want to have try-catch nesting...) :
try{ // something // u can do what u want here }catch(Exception e){ // do things }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With