Search code examples
javaexceptionsqlexceptionchaininginstanceof

Can Exception.getCause() be used to know the chained Exception?


My code look like this:

    SQLException sqlExc;
    //resX is obtained from the method signature and it's a ResourceException
    Exception linkedExc = resX.getLinkedException();
    // if linkedExc exception is a SQL Exception, assign it to sqlExc
    if (linkedExc instanceof SQLException) {
        sqlExc = (SQLException) linkedExc;
    }

Would changing

Exception linkedX = resX.getLinkedException();

to

Exception linkedX = new Exception(resX.getCause());

give the same result? or the type of Exception would not be kept in the newly created exception?

If not what is the best way to do it?

This is a 15 years old code, that is why it's using deprecated methods. I'm trying to fix that.


Solution

  • The answer is yes. The below code is proving it. You can use it as written here or as you wrote it. Both should pass the if statement.

    import java.sql.SQLException;
    import javax.resource.ResourceException;   
    
    public class Linking {
    
        public static void main(String[] args) {
    
            SQLException resW = new SQLException("blubb");
            ResourceException resX = new ResourceException("a message", resW);
            SQLException sqlExc = null;
            Throwable linkedExc = resX.getCause();
    
            // if linkedExc exception is a SQL Exception, assign it to sqlExc
            if (linkedExc instanceof SQLException) {
                sqlExc = (SQLException) linkedExc;
            }           
            if (sqlExc != null)
                sqlExc.printStackTrace();
        }    
    }
    

    The documentation on ResourceException ( http://docs.oracle.com/javaee/1.4/api/javax/resource/ResourceException.html#setLinkedException%28java.lang.Exception%29 ) says:

    Deprecated. J2SE release 1.4 supports a chained exception facility that allows any throwable to know about another throwable, if any, that caused it to get thrown. Refer to getCause and initCause methods of the java.lang.Throwable class.