Why, in an attempt to finally catch, is returning finally?

What happens to return A code in my catch block?

 public class TryCatchFinallyTest { @Test public void test_FinallyInvocation() { String returnString = this.returnString(); assertEquals("B", returnString); } String returnString() { try { throw new RuntimeException(""); } catch (RuntimeException bogus) { System.out.println("A"); return "A"; } finally { System.out.println("B"); return "B"; } } } 
+4
source share
5 answers

Finally, execution is performed immediately before any return / exit from the method. Therefore when you do

 return "A"; 

runs like this:

 System.out.println("B");//Finally block return "B";//Finally block return "A";//Return from exception catch 

And thus, "B" is returned, not "A"

+3
source

Perhaps return "A"; optimized by the compiler, maybe not, and "A" is simply dynamically replaced. It doesn't really matter, since you shouldn't have this code.

This is one of the classic examples of problems using finally for control flows: you lose some instructions, and the other encoder may not see the "intent" (in fact, it can only be an error or harm).

You may have noticed that javac gives the warning "the final block does not complete normally."

Do not return to finally clause

+3
source

the finally block will always be executed, and the catch block will only be executed if an exception is detected.

0
source

Before return "A" the finally block will be called, which will be return "B" , and your return "A" will be skipped and will never be executed. Its because the finally block is always executed before the return method, and if you return something from the finally block, the return your try/catch will always be skipped.

Note. Returning from the finally block is not good practice for a Java programmer. The JAVA Compiler also shows you a warning, because the " finally block does not complete normally " if you are returning something from the finally block.

0
source

Finally

You can attach a finally clause to a try-catch block. The code inside the finally clause will always execute, even if the exception is thrown from a try or catch block. If your code has a return statement inside a try or catch block, the code inside the finally block will be executed after returning from the method.

Links http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html

0
source

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


All Articles