Important finally block questions which are commonly asked in interviews.
1) Find the output of below program ?
try {
System.out.println("Try block");
System.exit(0);
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
System.out.println("finally block!!!");
}
Output
Try block
Reason:-the program will not execute finally block in this case because program is terminated using
System.exit(0) statement.
2) Find the output of below program ?
try {
System.out.println("Try block");
System.out.println(10 / 0);
System.exit(1);
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
System.out.println("Finally block!!!");
}
Output
Try block
java.lang.ArithmeticException: / by zero
at FinallyTest.main(FinallyTest.java:16)
Finally block!!!
Reason:- An arithmetic exception occurred before executing statement System.exit(1).
3) Find the output of below program ?
public class FinallyTest {
public static void main(String a[]) {
System.out.println(tryCatchMethod());
}
private static int tryCatchMethod() {
try {
return 1;
} finally {
System.out.println("finally block");
}
}
}
Output
finally block
1
Reason:-finally block runs before method returns 1 .
4) Find the output of below program ?
public class FinallyTest {
public static void main(String a[]) {
System.out.println(getIntegerNumber());
}
private static int getIntegerNumber() {
try {
return 1;
} finally {
return 2;
}
}
}
Output
2
Reason:- return value in finally block ("2") overrides return value of try block ("1").
5) Find the output of below program ?
public class FinallyTest {
public static void main(String a[]) {
System.out.println(getIntegerNumber());
}
private static int getIntegerNumber() {
try {
throw new NumberFormatException();
} finally {
return 2;
}
}
}
Output
2
Reason:-Exception thrown by try block is overridden by return statement in finally block.That is why no exception is thrown.So Its bad practice to use return statements in finally block.
6)
public class FinallyTest {
public static void main(String a[]) {
System.out.println(getIntegerNumber());
}
private static int getIntegerNumber() {
int i = 0;
try {
i = 1;
return i;
} finally {
i = 2;
System.out.println("finally block.");
}
}
}
Output
finally block.
1
Reason:- when return i is executed i has a value 1 after that i is assigned new value in finally block to 2 and program prints "finally block.". but here 1 is returned because return statement is not executed again.
Enjoy programming :)