0

Is there a way to know in finally that exception is thrown, without using any extra variable as below:

 boolean hasFailed = true;
 try { // code

     //...
     hasFailed = false;
  } finally {
      if (hasFailed) {
         // handle failure
      }
   }

Similarly, also without adding exception variable (using catch clause), I didn't find answer in similar questions

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • 6
    No; use a `catch` block. – SLaks Dec 14 '18 at 14:09
  • @SLaks also with catch block, how to not use extra variable? – Ori Marko Dec 14 '18 at 14:10
  • @Lorelorelore there is not such option in answers – Ori Marko Dec 14 '18 at 14:13
  • 1
    @user7294900: what is the issue with having 1 "extra" boolean flag? Just use the normal `try`/`catch` flow and set the flag to `true` in the catch block. I would also suggest logging the error in non-trivial code. – derekmckinnon Dec 14 '18 at 14:23
  • @derekmckinnon can't finally block know exception is thrown? – Ori Marko Dec 14 '18 at 14:28
  • 1
    @user7294900 No. That's not how the language was designed. – derekmckinnon Dec 14 '18 at 14:29
  • @derekmckinnon there is unhandled exception handler as https://stackoverflow.com/questions/588634/is-there-an-unhandled-exception-handler-in-java – Ori Marko Dec 14 '18 at 14:32
  • An `UncaughtExceptionHandler` is only called when the `Thread` is about to _terminate_ because no other code caught the exception. – Slaw Dec 14 '18 at 14:37
  • @user7294900 You should just use the language as it was intended instead of trying to make it work the way you think it should. As slaw mentioned, the mechanism you are referring to is not meant for this and is a hack. Anyone maintaining code after you will hate their existence if you do this...trust me – derekmckinnon Dec 14 '18 at 14:41

0 Answers0