Java Throwable initCause() 方法

2024 年 11 月 9 日 | 阅读 2 分钟

Java Throwable 类的 initCause() 方法用于使用指定的异常初始化调用 Throwable 的原因。此方法只能调用一次。如果调用 Throwable 是通过 Throwable(Throwable) 或 Throwable(String, Throwable) 创建的,则此方法一次都不能调用。

语法

参数

由 getCause() 方法返回的 Throwable 实例,它将被初始化为调用 Throwable 的原因。

返回

调用 Throwable 实例的引用。

示例 1

输出

Cause : java.lang.ArithmeticException: / by zero

示例 2

输出

Exception in thread "main" javaException: This is new java Exception!!
	at ThrowableInitCauseExample2.func1(ThrowableInitCauseExample2.java:14)
	at ThrowableInitCauseExample2.main(ThrowableInitCauseExample2.java:4)
Caused by: newException: This is another new exception!!
	at ThrowableInitCauseExample2.func2(ThrowableInitCauseExample2.java:20)
	at ThrowableInitCauseExample2.func1(ThrowableInitCauseExample2.java:12)
	... 1 more