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?
Failing to catch an exception will likely cause the program to terminate, but the act of throwing one will not.
It always executes, regardless of whether an exception was thrown or caught. You can nest one or more try statements.
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.
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.
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
}
}
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