Consider the code below:
try { // block of code to monitor for errors // the code you think can raise an exception } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // optional finally { // block of code to be executed after try block ends }
The finally block is optional. It always gets executed whether an exception occurred in try block or not . If an exception occurs, then it will be executed after try and catch blocks. And if exception does not occur then it will be executed after the try 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.
Find the output for the code given below:
// Java program to demonstrate // control flow of try-catch-finally clause // when exception occur in try block // and handled in catch block class InterviewBit { public static void main (String[] args) { // array of size 10. int[] arr = new int[10]; try { int i = arr[11]; System.out.print("A" + " "); } catch(ArrayIndexOutOfBoundsException ex) { System.out.print("B" + " "); } finally { System.out.print("C" + " "); } // rest program will be executed System.out.println("D"); } }