Java - Exception Exception Rethrowing

Introduction

An exception can be rethrown.

The following code catches the exception, prints its stack trace, and rethrows the same exception.

When the same exception object is rethrown, it preserves the details of the original exception.

try {
   // Code that might throw MyException
}
catch(MyException e) {
   e.printStackTrace(); // Print the stack trace

   // Rethrow the same exception
   throw e;
}

Rethrowing an Exception to Hide the Location of the Original Exception

Demo

public class Main {
  public static void main(String[] args) {
    try {/*  w  w  w.j a va2 s .  com*/
      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);
  }
}

Result