Nested try Statements

The try statement can be nested.


public class Main {
  public static void main(String args[]) {
    try {
      int a = args.length;
      int b = 42 / a;
      System.out.println("a = " + a);
      try { // nested try block
        if (a == 1)
          a = a / (a - a); // division by zero exception
        if (a == 2) {
          int c[] = { 1 };
          c[4] = 9; // an out-of-bounds exception
        }
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index out-of-bounds: " + e);
      }
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    }
  }
}
Home 
  Java Book 
    Language Basics  

Exception Handler:
  1. Exception Handling
  2. Exception Types
  3. try and catch
  4. Displaying a Description of an Exception
  5. Multiple catch Clauses
  6. Nested try Statements
  7. Creates and throws an exception
  8. Methods with throws clause
  9. finally
  10. Java's Built-in Exceptions
  11. Creating Your Own Exception Subclasses
  12. Chained Exceptions