This block will execute every time, though if try-catch block does not works. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having clean-up code accidentally bypassed by a return, continue, or break. Putting clean-up code in a finally block is always a good practice, even when no exceptions are anticipated.
Let’s understand through below example…
We have taken three cases –
Case 1: any type of exception not occurred
Case 2: exception occur and handled by the ‘catch’ block.
Case 3: exception occur but not handled by the catch block.
Case 1:
class final1{ public static void main(String[] args) { int a=0; try { a=90/10; } catch (Exception e) { System.out.println(e); } finally{ System.out.println(“finally block excuted!!”); } } } |

case 2:
class final2 { public static void main(String[] args) { int a=0; try{ a=90/0; } catch(ArithmeticException e){ System.out.println(e); } finally{ System.out.println(“finally block executed!!”); } } } |

case 3:
class final3 { public static void main(String[] args) { int a=0; try{ a=90/0; } // here exception will ‘ArithmeticException’ catch(ArrayIndexOutOfBoundsException e){ System.out.println(e); } finally{ System.out.println(“finally block still executed!!”); } } } |
