简体   繁体   English

可以使用Exception.getCause()来了解链接的Exception吗?

[英]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? 还是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. 这是一个已有15年历史的代码,这就是为什么它使用不推荐使用的方法的原因。 I'm trying to fix that. 我正在尝试解决此问题。

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. 两者都应通过if语句。

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: 关于ResourceException的文档( http://docs.oracle.com/javaee/1.4/api/javax/resource/ResourceException.html#setLinkedException%28java.lang.Exception%29 )说:

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. J2SE版本1.4支持链式异常功能,该功能允许任何throwable知道导致其被抛出的另一个throwable(如果有)。 Refer to getCause and initCause methods of the java.lang.Throwable class. 请参阅java.lang.Throwable类的getCause和initCause方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM