Search code examples
javaexceptiontry-catch

Java run code only if no exception is thrown in try and catch block?


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

Solution

  • 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.