What’s the cause of your problem?

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();
    }
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.