Can I use uncaughtexceptionhandler to move to next block of codes?

132 views Asked by At

Can I use uncaughtexceptionhandler to ignore the exception and move forward? If I can, how to write that handler?

for example:

try{
  //something
}catch(exception e){
  //something
}

//AND WHEN SOME UNCAUGHT EXCEPTION APPEAR, IGNORE EXCEPTION AND MOVE TO NEXT STEP

try{
  //something else
}catch(exception e){
  //something else
}

thank you for your attention

1

There are 1 answers

0
zapl On BEST ANSWER

You can use the try .. (catch) .. finally construct to execute code even if an exception was thrown but not handled.

try {
    // do things that can throw an exception
} finally {
    // this block is !always! executed. Does not matter whether you
    // "return"ed, an exception was thrown or everything was just fine.
}

if you add a catch in there then execution order is try up to the point where the exception happened, then the first appropriate catch block, then the finally block.

If you want to execute code in the finally block only if there was no exception, set some flag as the last operation of the try block.

boolean doFinally = true;
try {
    // flag stays "true" if something throws here
    doFinally = false;
} finally {
    if (doFinally) {
        // do something
    }
}

Note: if you don't catch an otherwise uncaught exception somewhere your app will still crash after it has exectued the code in finally.