Java program to demonstrate the use of nested try and catch blocks
Codeaft.java
classCodeaft{publicstaticvoidmain(Stringargs[]){Strings=null;intn=515,d=0,result=0;try{try{result=n/d;}catch(ArithmeticExceptione){System.out.println("Exception caught in the first nested catch block");}System.out.println("Length: "+s.length());}catch(ArithmeticExceptione){System.out.println("Exception caught in the first catch block");}catch(Exceptione){System.out.println("Exception caught in the third catch block");}}}
Output
codeaft@codeaft:~$ javac Codeaft.java codeaft@codeaft:~$ java Codeaft
Exception caught in the first nested catch block
Exception caught in the third catch block
codeaft@codeaft:~$
Java program to demonstrate the use of nested try and catch blocks
Codeaft.java
classCodeaft{publicstaticvoidmain(Stringargs[]){Strings=null;intn=515,d=0,result=0;try{System.out.println("Length: "+s.length());}catch(ArithmeticExceptione){System.out.println("Exception caught in the first catch block");}catch(Exceptione1){try{result=n/d;}catch(ArithmeticExceptione2){System.out.println("Exception caught in the first nested catch block");}System.out.println("Exception caught in the third catch block");}}}
Output
codeaft@codeaft:~$ javac Codeaft.java codeaft@codeaft:~$ java Codeaft
Exception caught in the first nested catch block
Exception caught in the third catch block
codeaft@codeaft:~$
Java program to demonstrate the use of nested try, catch, and finally blocks
Codeaft.java
classCodeaft{publicstaticvoidmain(Stringargs[]){Strings=null;intn=515,d=0,result=0;try{System.out.println("Length: "+s.length());}catch(ArithmeticExceptione){System.out.println("Exception caught in the first catch block");}catch(Exceptione1){try{result=n/d;}catch(ArithmeticExceptione2){System.out.println("Exception caught in the first nested catch block");}finally{System.out.println("Finally block will always execute");}System.out.println("Exception caught in the third catch block");}finally{System.out.println("Finally block will always execute");}}}
Output
codeaft@codeaft:~$ javac Codeaft.java codeaft@codeaft:~$ java Codeaft
Exception caught in the first nested catch block
Finally block will always execute
Exception caught in the third catch block
Finally block will always execute
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.