Catch different Exception types : try catch « Statement Control « Java Tutorial






class MyException extends Exception {
  MyException() {
    super("My Exception");
  }
}

class YourException extends Exception {
  YourException() {
    super("Your Exception");
  }
}

class LostException {
  public static void main(String[] args) {
    try {
      someMethod1();
    } catch (MyException e) {
      System.out.println(e.getMessage());
    } catch (YourException e) {
      System.out.println(e.getMessage());
    }
  }

  static void someMethod1() throws MyException, YourException {
    try {
      someMethod2();
    } finally {
      throw new MyException();
    }
  }

  static void someMethod2() throws YourException {
    throw new YourException();
  }
}








4.10.try catch
4.10.1.catch divide-by-zero error
4.10.2.Handle an exception and move on.
4.10.3.Demonstrate multiple catch statements.
4.10.4.Catch different Exception types
4.10.5.An example of nested try statements.
4.10.6.Try statements can be implicitly nested via calls to methods