InterviewSolution
Saved Bookmarks
| 1. |
Can try statements be nested in Java? |
|
Answer» Yes, try statements can be nested in Java. A try block within a try block is called nested try block. The syntax for a nested try block is as follows: try // outer try block { statements; try // inner try block { statements; } CATCH(Exception e) // inner catch block { } } catch(Exception x) // outer catch block { }The following is an example for nested try block: public CLASS Example { public STATIC void main(String[] args) { int[] n={1,2,3,4,5,6}; int[] d={1,2,0,3}; for(int i=0;i<n.length;i++) { try { try { System.out.println(n[i]+"/"+d[i]+"="+n[i]/d[i]); } catch(ARITHMETICEXCEPTION e) { System.out.println("Division by zero not Possible"); } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array Index is out of bounds"); } } } }The output is: $javac Example.java $java Example 1/1 = 1 2/2 = 1 Division by zero not Possible 4/3 = 1 Array Index is out of bounds Array Index is out of bounds |
|