How do I make it so the code runs only if there was no exception thrown?
With finally code runs whether there was an exception or not.
try { //do something } catch (Exception e) {} //do something only if nothing was thrown
The code in the try block is executed first, and if it throws an exception, the code in the catch block will be 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.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.
throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
Here are two ways:
try { somethingThatMayThrowAnException(); somethingElseAfterwards(); } catch (...) { ... }
Or if you want your second block of code to be outside the try
block:
boolean success = false; try { somethingThatMayThrowAnException(); success = true; } catch (...) { ... } if (success) { somethingElseAfterwards(); }
You could also put the if
statement in a finally
block, but there is not enough information in your question to tell if that would be preferable or not.
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