Most of exceptions has a few constructors including those with cause exception.
But what if you have to throw an exception that has no cause in constructor? You try to survive:
Exception cause = new Exception("I'm the cause!");
SSLHandshakeException noCauseExc = new SSLHandshakeException(String.format("SSL problem: [%s]", cause.getMessage()));
noCauseExc.printStackTrace();
...and you
lose stacktrace which is
crucial!
There's a solution
Throwable::initCause(). Check this code and have cause tailed to your exception
import javax.net.ssl.SSLHandshakeException;
/**
* Created by bartek on 04.09.15.
*/
public class Cause {
public static void main(String[] args) {
Exception cause = new Exception("I'm the cause!");
SSLHandshakeException noCauseExc = new SSLHandshakeException(String.format("SSL problem: [%s]", cause.getMessage()));
noCauseExc.printStackTrace();
SSLHandshakeException withCauseExc = new SSLHandshakeException("Another SSL problem");
withCauseExc.initCause(cause);
withCauseExc.printStackTrace();
}
}
Having read this I thought it was extremely enlightening.
I appreciate you taking the time and energy to put this short article together.
I once again find myself spending a lot of time both reading
and posting comments. But so what, it was still worthwhile!