簡體   English   中英

Throwable類的getCause()函數(在Java中)未按預期工作

[英]getCause() function of Throwable class (in Java) is not working as expected

我在調用ThrowablegetCause函數時得到null。

package com.salman.demo;
public class MyClass {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            NormalClass.testIt();
        } catch (Throwable th) {
            System.out.println(th.getCause());
        }
    }
}


package com.salman.demo;

import com.salman.exceptions.ValidationException;

public class NormalClass {
    public static void testIt() throws ValidationException {
        System.out.println("Inside testIt funtion.");

        throw new ValidationException("Validation Exception..");
    }
}

在運行MyClass ,它將輸出以下輸出

Inside testIt funtion.
null

但是,在調試此代碼時,我可以看到cause私有變量的值設置為ValidationException ,這是預期的,但是在調用該私有字段的getter時會返回null。

ValidationException你扔將是th在調用代碼...有這個問題並沒有引起ValidationException getCause()的要點是,一個異常能夠將另一異常作為根本原因-但您的情況只有一個異常。

您看到私有cause變量的值是ValidationException的事實與該字段的記錄方式完全一致(強調我的意思):

導致引發此throwable的throwable;如果throwable不是由另一個throwable引起的,或者如果引起原因的throwable未知,則為null。 如果此字段等於此throwable本身,則表明此throwable的原因尚未初始化。

這就是為什么getCause()實現為:

return (cause==this ? null : cause);

如果您希望看到預期的鏈接有效,則可以創建兩個異常,一個鏈接到另一個:

throw new ValidationException("Validation Exception..",
    new IllegalArgumentException("Bang!"));

現在在ValidationException上調用getCause()將返回IllegalArgumentException

您可能只想更改您的調用代碼以登錄th而不是th.getCause()

您的例外是該鏈中的第一個例外,因此沒有原因。

如果要測試,則需要具有異常鏈,因此請阻止其中的一個並拋出使用前一個構造的新異常。

暫無
暫無

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

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