Java program to demonstrate the use of finally block
Codeaft.java
classCodeaft{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
codeaft@codeaft:~$ javac Codeaft.java codeaft@codeaft:~$ java Codeaft
Exception caught in the second catch block
Finally block always get executed
codeaft@codeaft:~$
The following try and finally block sequence is allowed
Codeaft.java
classCodeaft{publicstaticvoidmain(Stringargs[]){Strings=null;try{System.out.println("Length: "+s.length());}finally{System.out.println("Finally block always get executed");}}}
Output
codeaft@codeaft:~$ javac Codeaft.java codeaft@codeaft:~$ java Codeaft
Finally block always get executed
Exception in thread "main" java.lang.NullPointerException
at Codeaft.main(Codeaft.java:8)
codeaft@codeaft:~$
Dear User, Thank you for visitng Codeaft. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.