Never lost stack trace while rethrowing exceptions in Java

Exception are most useful information when any error occurs in any application. I have see lots of Java application is lost the original exception and rethrow their own exception.
Due to this it will became very hard to find the root cause of the exception.

2 Likes

Bad way to Rethrow the Exception

try{
// write your logic here
}catch(Exception e){
  throw MyNewExcpetion("Some Error Occured at service side").
// throw MyNewExcpetion("Some Error Occured at service side","ERROR_615").
}

Good Way to Rethrow the Exception

try{

}catch(Exception e){
  // throw e;
throw MyNewExcpetion("Some Error Occured at service side", e).
}

//keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:

Good Custom Exception Class Sample

public class MyException extends RuntimeException {

    public MyException(String message) { // use when throw some logical exception.
        super(message);
    }

    public MyException(String message, Throwable th) { // always use this when rethrowing
        super(message, th);
    }
}
3 Likes

Very good insight on Java programming

1 Like