Friday, November 11, 2011

Statement Control » throw

Demonstrate throw
class ThrowDemo {
  static void demoproc() {
    try {
      throw new NullPointerException("demo");
    catch (NullPointerException e) {
      System.out.println("Caught inside demoproc.");
      throw e; // rethrow the exception
    }
  }

  public static void main(String args[]) {
    try {
      demoproc();
    catch (NullPointerException e) {
      System.out.println("Recaught: " + e);
    }
  }
}
 
Change Exception type and rethrow
class MyException extends Exception {
  MyException() {
    super("My Exception");
  }
}

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

class ChainDemo {
  public static void main(String[] args) {
    try {
      someMethod1();
    catch (MyException e) {
      e.printStackTrace();
    }
  }

  static void someMethod1() throws MyException {
    try {
      someMethod2();
    catch (YourException e) {
      System.out.println(e.getMessage());
      MyException e2 = new MyException();
      e2.initCause(e);
      throw e2;
    }
  }

  static void someMethod2() throws YourException {
    throw new YourException();
  }
}
 
http://www.java2s.com/Tutorial/Java/0080__Statement-
Control/Catalog0080__Statement-Control.htm
 
 
 

No comments:

Post a Comment