Thursday, February 20, 2014

Java : Few basic things to know about "finally" block in Exception handling

finally block is used to as cleanup facility in case of program abruptly interrupts due to exception. e.g. Closing I/O resources, closing connection etc.

Lets find out more details about finally block and answers to few basic questions.
Question 1: Can we write try block without catch?
Answer: Yes. we can write try - finally block as shown in below code example.

Question 2 : Whether finally block is executed if exception is thrown from try block?
Answer : Yes. Code in finally block will be executed even if exception is thrown from try block.

Question 3: Exception A is thrown from try block and while executing finally block, exception B is thrown. Which exception will be thrown to calling method?
Answer : Exception B which is thrown from finally block. Exception thrown from try block is discarded

Code to verify above scenarios:


/**
* Program to show how exception in try block is discarded if there is exception in finally block
*/
public class TestException {

public static void main(String[] args) {
try {
testException();
} catch (Exception e) {
System.out.println(e);
}

}

public static void testException(){
Integer j = null;
Integer k;
String [] strArray = new String []{"aa"};
try {
System.out.println("In try");
//ArrayIndexOutOfBoundsException will be thrown from below code
String testStr = strArray[1];
}
finally{
System.out.println("in finally");
//NullPointerException will be thrown from below code as j is null.
k = j *10;
}
}

}

Output after program execution:

In try
in finally
java.lang.NullPointerException