finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.
The finally block will execute whether or not exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handlers and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning.
The finally clause is optional. However, each try statement requires at least one catch or a finally clause.
Example:
class FinallyDemo
{ static void procA()
{ try
{ System.out.println("inside procA()");
throw new RuntimeException("Demo");
}
finally
{ System.out.println("procA()'s finally"); }
}
static int procB()
{ try
{ System.out.println("inside procB()");
return(5);
}
finally
{ System.out.println("procB()'s finally"); return(10);
}
}
static void procC()
{ try
{ System.out.println("inside procC()"); }
finally
{ System.out.println("procC()'s finally"); }
}
public static void main(String args[])
{ try
{ procA(); }
catch(Exception e)
{ System.out.println("! Exception caught:"+e); }
int x = procB();
System.out.println("x= "+x);
procC();
}
}
Output:
inside procA()
procA()'s finally
! Exception caught:java.lang.RuntimeException: Demo
inside procB()
procB()'s finally
x= 10
inside procC()
procC()'s finally
Example:
class FinallyDemo
{ static void procA()
{ try
{ System.out.println("inside procA()");
throw new RuntimeException("Demo");
}
finally
{ System.out.println("procA()'s finally"); }
}
static int procB()
{ try
{ System.out.println("inside procB()");
return(5);
}
finally
{ System.out.println("procB()'s finally"); return(10);
}
}
static void procC()
{ try
{ System.out.println("inside procC()"); }
finally
{ System.out.println("procC()'s finally"); }
}
public static void main(String args[])
{ try
{ procA(); }
catch(Exception e)
{ System.out.println("! Exception caught:"+e); }
int x = procB();
System.out.println("x= "+x);
procC();
}
}
Output:
inside procA()
procA()'s finally
! Exception caught:java.lang.RuntimeException: Demo
inside procB()
procB()'s finally
x= 10
inside procC()
procC()'s finally
No comments:
Post a Comment