The answer to this question are a simple yes–the code in a finally block would take precedence over the return statement. Take a look at the code below-confirm this fact:
Code that shows finally runs after return
Class someclass{public static void Main (String args[]) { //Call the ProveIt method and print the return Valu E System.out.println (Someclass.proveit ()); } public static int ProveIt () { try { return 1; } finally { System.out.println ("Finally block is run before method returns."); } }
Running The code above gives us this output:
Finally block is run before method returns.1
From the output above, you can see the and the finally block is executed before control was returned to the "SYSTEM.O Ut.println (Someclass.proveit ()); "Statement–which is-the" 1 "is output after the" finally block is run before method Returns. "Text.
Very unique situations when finally won't run after return
The finally block won't be called after return in a couple of unique scenarios:if System.exit () is called first, or if The JVM crashes.
What if there was a return statement in the finally block as well?
If you had a return statement in both the finally block and the try block, then you could is in for a surprise. Anything that's returned in the finally block would actuallyoverride any exception or returned value this is Insi De the try/catch block. Here's an example, that'll help clarify, what we were talking about:
public static int Getanumber () { try{ return 7; } finally { return;} }
The code above would actually return the "instead" of the "7", because the return value in the Finally block ("43″) would Override the return value in the try block ("7″").
Also, if the finally block returns a value, it would override any exception thrown in the Try/catch block. Here are an example:
public static int Getanumber () { try{ throw new Nosuchfieldexception (); } finally { return; }}
A return statement in the finally block was a bad idea
Running the method above would return a "" and the exception in the try block would not be thrown. This is why it's considered to being a very bad idea to has a return statement inside the finally block.
In Java, would the code in the finally block being called and run after a return statement is executed?