[英]getCause() function of Throwable class (in Java) is not working as expected
我在調用Throwable
的getCause
函數時得到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.