Rethrowing an Exception to Hide the Location of the Original Exception - Java Object Oriented Design

Java examples for Object Oriented Design:Exception

Description

Rethrowing an Exception to Hide the Location of the Original Exception

Demo Code

public class Main {
  public static void main(String[] args) {
    try {/*from  ww w  .  j  av a  2  s .c  om*/
      m1();
    } catch (MyException e) {
      // Print the stack trace
      e.printStackTrace();
    }
  }

  public static void m1() throws MyException {
    try {
      m2();
    } catch (MyException e) {
      e.fillInStackTrace();
      throw e;
    }
  }

  public static void m2() throws MyException {
    throw new MyException("An error has occurred.");
  }
}

class MyException extends Exception {
  public MyException() {
    super();
  }

  public MyException(String message) {
    super(message);
  }

  public MyException(String message, Throwable cause) {
    super(message, cause);
  }

  public MyException(Throwable cause) {
    super(cause);
  }
}

Related Tutorials