"finally" Clause(Exception handling in Java)
finally
An exception can force a program to follow a non-linear path and it can bypass few statements. For example, a connection with the database is opened and then some exception occurs. The program will terminate eventually, and the connection will still remain open. The "finally" block, can be used to close this connection.
The "finally" block guarantees that the statement will be executed in all circumstances. The "finally" block is particularly useful for closing open Java IO streams and database connections in a program.
The syntax for finally is,
try { //Statements }catch(SomeException se) { //handle exception } finally { //TO-DO }
try { //statements finally { // TO-DO }
Example
/******************First example***********/ public class FinallyDemo { public static void main(String[] args) { System.out.println("Start Statement"); int a=10; try { for(int i=-3;i<=2;i++) { System.out.println("div"+(5/i)); } }finally //try-finally { System.out.println("Finally 'clause' executed"); } System.out.println("End Statement"); } } Output: Start Statement div-1 div-2 div-5 Finally 'clause' executed Exception in thread "main" java.lang.ArithmeticException: / by zero at FinallyDemo.main(FinallyDemo.java:9)
/******************Second example***********/ public class FinallyDemo { public static void main(String[] args) { System.out.println("Start Statement"); int a=10; try { for(int i=-3;i<=2;i++) { System.out.println("div"+(5/i)); } }catch(ArithmeticException ae) { System.out.println("Arithmetic exception occured"); } finally //try-catch-finally { System.out.println("Finally 'clause' executed"); } System.out.println("End Statement"); } } Output: Start Statement div-1 div-2 div-5 Arithmetic exception occured Finally 'clause' executed End Statement