Java Reference

Java Reference Home | Smart Soft Home

finally

Description

The finally keyword does not stand alone. It must be used immediately following a try/catch block. Any code placed in the finally block is guaranteed to execute - exception or no exception - even if a return or throw appear in the try or catch block. If there is no return or throw in the try or catch blocks, then finally has no effect different from simply placing code after the try/catch.

Basically, finally short circuits the return or throw so that the finally block always executes - exception or no exception.

Example

try{
  String s="X";
  int i=Integer.parseInt(s);
}
catch(NumberFormatException ex){
  System.out.println(s + " can't be converted to an int");
  return;
}
finally{
  System.out.println("This always gets executed");
}