Java quick suggestion crashes

Is there a way to detect within the finally clause that an exception is in the process of being thrown?

t

try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } 

or ignores one of the exceptions, the only thing you can do. In C ++, it does not even allow you to ignore one of the exceptions and simply calls terminate (). Most other languages ​​use the same rules as java.

+4
source share
5 answers

Set the flag variable, then check it in the finally clause, for example:

 boolean exceptionThrown = true; try { mightThrowAnException(); exceptionThrown = false; } finally { if (exceptionThrown) { // Whatever you want to do } } 
+13
source

If you do this, you may have a problem with your design. The idea of ​​a β€œfinal” block is that you want to do something regardless of how the method exits. It seems to me that you don't need a finally block at all, and you just need to use try-catch blocks:

 try { doSomethingDangerous(); // can throw exception onSuccess(); } catch (Exception ex) { onFailure(); } 
+10
source

If the function throws and you want to catch the exception, you have to wrap the function in a try block, this is the safest way. So in your example:

 try { // ... } finally { try { SomeCleanupFunctionThatThrows(); } catch(Throwable t) { //or catch whatever you want here // exception handling code, or just ignore it } } 
+1
source

Do you want the finally block to act differently depending on the successful completion of the try block?

If so, you can always do something like:

 boolean exceptionThrown = false; try { // ... } catch(Throwable t) { exceptionThrown = true; // ... } finally { try { SomeCleanupFunctionThatThrows(); } catch(Throwable t) { if(exceptionThrown) ... } } 

This gets pretty confusing though ... you might think of a way to restructure your code to make it unnecessary.

0
source

No, I don’t believe that. The catch block will be completed before the final block.

 try { // code that may or may not throw an exception } catch { // catch block must exist. finally { SomeCleanupFunctionThatThrows(); // this portion is ran after catch block finishes } 

Otherwise, you can add a synchronize () object that will be used by the exception code, which you can check in the finally block to help you determine if an exception is being thrown in a separate thread.

-1
source

Source: https://habr.com/ru/post/1276710/


All Articles