Friday, September 4, 2015

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 cruicial!

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

No comments:

Post a Comment