Java Throwable initCause() method

The initCause() method of Java Throwable class is used to initialize the cause of the calling Throwable with the specified cause. This method can be called only once. If the calling Throwable is created by using Throwable(Throwable) or Throwable(String, Throwable), then this method cannot be called even once.

Syntax

Parameter

A Throwable instance returned by getCause() method, which is to be initialized to the calling Throwable as a cause.

Return

A reference to the calling Throwable's instance.

Example 1

Output:

Cause : java.lang.ArithmeticException: / by zero

Example 2

Output:

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