Finally
Preethi Pattabiraman
Experienced Backend Developer | Java & Cloud Solutions Expert | Building Scalable AWS Applications | Continuous Learner & Team Collaborator
Many of the interview questions are aimed to make us pause. But, if you note those little pointers, it will be a cakewalk.
The finally block executes every time: if exception occurs, if it does not occur, if exception is handled, if it is not handled.
Take a look at the below example:
public class Main
{
? ? public static int getReturnValue(int r) {
? ? ? ? int returnVal = r;
? ? ? ? try {
? ? ? ? ? ? if(returnVal == 3) {
? ? ? ? ? ? ? ? throw new Exception("I am an exception");
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println("Return from try");
? ? ? ? ? ? return returnVal;
? ? ? ? }
? ? ? ? catch(Exception e) {
? ? ? ? ? ? returnVal = 0;
? ? ? ? ? ? System.out.println("Return from catch");
? ? ? ? ? ? return returnVal;
? ? ? ? }
? ? ? ? finally {
? ? ? ? ? ? returnVal = -1;
? ? ? ? ? ? System.out.println("Return from finally");
? ? ? ? ? ? return returnVal;
? ? ? ? }
? ? }
? ??
public static void main(String[] args) {
System.out.println(getReturnValue(1));
}
}
In exception handling, the finally block always executes. Even if there are no exceptions, finally always executes.
Hence the above program always returns -1.
Finally can be used to add some really important code like cleaning up, closing resources etc.