Filling in new trace information in the stack trace of an Exception

The stack trace is useful to determine where the exception was thrown. There may be times where you need to rethrow an exception and find out where it was rethrown. You can use the method fillInStackTrace for that.

Main.java:

public class Main {
   public static void main(String args[]) {
      try {
         methodWithException1();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void methodWithException1() throws Exception {
      try {
         methodWithException2();
      }
      catch(Exception e) {
         throw (Exception) e.fillInStackTrace();
//         throw e;
      }
   }
 
   public static void methodWithException2() throws Exception {
      throw new Exception("some extra info");
   }
}

outputs:

java.lang.Exception: some extra info
        at Main.methodWithException1(Main.java:16)
        at Main.main(Main.java:4)

If you would have written throw e instead of throw (Exception e.fillInStackTrace, the output would have been:

java.lang.Exception: some extra info
        at Main.methodWithException2(Main.java:22)
        at Main.methodWithException1(Main.java:13)
        at Main.main(Main.java:4)