簡體   English   中英

可以使用Exception.getCause()來了解鏈接的Exception嗎?

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

我的代碼如下所示:

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

會改變

Exception linkedX = resX.getLinkedException();

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

給出相同的結果? 還是Exception類型不會保留在新創建的異常中?

如果不是,最好的方法是什么?

這是一個已有15年歷史的代碼,這就是為什么它使用不推薦使用的方法的原因。 我正在嘗試解決此問題。

答案是肯定的。 下面的代碼證明了這一點。 您可以按此處或按其編寫的方式使用它。 兩者都應通過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();
    }    
}

關於ResourceException的文檔( http://docs.oracle.com/javaee/1.4/api/javax/resource/ResourceException.html#setLinkedException%28java.lang.Exception%29 )說:

已過時。 J2SE版本1.4支持鏈式異常功能,該功能允許任何throwable知道導致其被拋出的另一個throwable(如果有)。 請參閱java.lang.Throwable類的getCause和initCause方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM