Am confused about how finally keyword actually works...
Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block willstill be executed even if there is a return statement somewhere in the try block.
when I run the code, I get 5 instead of 10 as I expected
public class Main {
static int count = 0;
Long x;
static Dog d = new Dog(5);
public static void main(String[] args) throws Exception {
System.out.println(xDog(d).getId());
}
public static Dog xDog(Dog d) {
try {
return d;
} catch (Exception e) {
} finally {
d = new Dog(10);
}
return d;
}
}
public class Dog {
private int id;
public Dog(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.
It identifies a block of statements that needs to be executed regardless of whether or not an exception occurs within the try block. It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block.
finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.
The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.
You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System. exit(0) method, at the end of the catch block which is just before the finally block.
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.
The finally block is executed not before the return statement, but before actual return. This means that the expression in return
statement is evaluated before the finally block is executed. In your case when you write return d
the d
expression is evaluated and stored into register, then finally
is executed and the value from that register is returned. There's no way to alter the content of that register.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With