CKTIS / Java
Throwable.getCause(): the cause of an exception
`getCause()` returns an exception’s immediate cause or `null`. Call it on an `ExecutionException` to inspect the exception thrown by the task.
Version: Java SE 21
Syntax
public Throwable getCause()Throwable.getCause() is a no-argument instance method on java.lang.Throwable. It returns the immediate cause as a Throwable, or null if the cause is absent or unknown. The default implementation reads the cause passed to a constructor or set through initCause(Throwable).
A single call follows just one link in the cause chain, not necessarily to the root cause. getMessage() returns the current object's detail message, while getSuppressed() reports a separate list of suppressed exceptions. Check the returned cause for null before using it, and check its type with instanceof before casting.
When a task fails by throwing an exception, Future.get() throws an ExecutionException. In the catch block, use getCause() to inspect the task's exception. Task cancellation (CancellationException) and interruption while waiting (InterruptedException) are separate cases.
Examples
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) throws InterruptedException {
FutureTask<Integer> task = new FutureTask<>(() -> {
throw new IllegalStateException("Missing input");
});
task.run();
try {
task.get();
} catch (ExecutionException failure) {
Throwable cause = failure.getCause();
System.out.println(failure.getClass().getSimpleName());
if (cause != null) {
System.out.println(cause.getClass().getSimpleName());
System.out.println(cause.getMessage());
}
}
}
}
Result
ExecutionException IllegalStateException Missing input
`run()` executes the task on the current thread. The subsequent `get()` throws `ExecutionException`; the program prints the wrapper type, the cause type, and the cause's message.
Related lessons
- Java · Lesson 50 · Intermediate · Version: 2