Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make code run only if an exception was thrown?

Tags:

java

exception

I have a try with several different catches after it. I have some "cleanup" code that only should be run if there was an exception thrown. I could add the same code to each exception, but that becomes a maintenance nightmare. Basically, I'd like something like the finally statement, but for it to only run if an exception was thrown.

Is this possible?

like image 824
Bromide Avatar asked Sep 27 '11 01:09

Bromide


People also ask

Does throwing an exception end the program?

Failing to catch an exception will likely cause the program to terminate, but the act of throwing one will not.

Does all the code in a try block execute if no exception is thrown?

It always executes, regardless of whether an exception was thrown or caught. You can nest one or more try statements.

How do I continue a program after catching an exception?

Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

Does the code after throw get executed?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.


1 Answers

There is no direct support for this unfortunately. How about something like this

boolean successful = false;
try {
    // do stuff
    successful = true;
} catch (...) {
    ...
} finally {
    if (!successful) {
        // cleanup
    }
}
like image 68
mpartel Avatar answered Oct 24 '22 11:10

mpartel