Java run code only if no exception is thrown in try and catch block?
try {
doSomething();
doSomething2();
} catch (Exception e) {
doSomething3();
}
In this example, doSomething2()
will only be executed if no exception is thrown by doSomething()
.
If an exception is thrown by doSomething()
, doSomething2();
will be skipped and execution will jump to doSomething3();
Also note, doSomething3()
will be executed if there is an exception thrown by doSomething2();
If no exception is thrown, doSomething3();
will not be executed.
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.