Java program to demonstrate the use of nested try and catch blocks
GD.java
classGD{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
godarda@gd:~$ javac GD.java godarda@gd:~$ java GD
Exception caught in the first nested catch block
Exception caught in the third catch block
godarda@gd:~$
Java program to demonstrate the use of nested try and catch blocks
GD.java
classGD{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
godarda@gd:~$ javac GD.java godarda@gd:~$ java GD
Exception caught in the first nested catch block
Exception caught in the third catch block
godarda@gd:~$
Java program to demonstrate the use of nested try, catch, and finally blocks
GD.java
classGD{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
godarda@gd:~$ javac GD.java godarda@gd:~$ java GD
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
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.