Java program to demonstrate the use of finally block
GD.java
classGD{publicstaticvoidmain(Stringargs[]){Strings=null;try{System.out.println("Length: "+s.length());}catch(ArithmeticExceptione){System.out.println("Exception caught in the first catch block");}catch(RuntimeExceptione){System.out.println("Exception caught in the second catch block");}catch(Exceptione){System.out.println("Exception caught in the third catch block");}finally{System.out.println("Finally block always get executed");}}}
Output
godarda@gd:~$ javac GD.java godarda@gd:~$ java GD
Exception caught in the second catch block
Finally block always get executed
godarda@gd:~$
The following try and finally block sequence is allowed
GD.java
classGD{publicstaticvoidmain(Stringargs[]){Strings=null;try{System.out.println("Length: "+s.length());}finally{System.out.println("Finally block always get executed");}}}
Output
godarda@gd:~$ javac GD.java godarda@gd:~$ java GD
Finally block always get executed
Exception in thread "main" java.lang.NullPointerException
at GD.main(GD.java:8)
godarda@gd:~$
Dear User, Thank you for visitng GoDarda. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.