Search code examples
javaexceptiontry-catch-finally

Flow control in Exception Handling


I am fairly new to Java and unable to understand the flow of control in try-catch-finally blocks. Whenever a exception is caught in a catch block, the code after the catch block is also executed, whether I place it in a finally block or not. Then what is the use of finally block?

class Excp
{
 public static void main(String args[])
 {
  int a,b,c;
  try
  {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Divided by zero"); 
  }
  System.out.println("After exception is handled");
 }
}

There is no difference if I place the last print statement inside the finally block.


Solution

  • It makes a difference if another exception (unhandled by your code) happens in the try/catch block.

    Without finally, the last line wouldn't be executed. With finally, the code is executed no matter what.

    This is particularly useful to perform cleanup tasks beyond the reach of the garbage collector: system ressource, database lock, file deletion etc...