Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Throwable: message, cause, and suppressed exceptions

java.lang.Throwable is the base of the exception and error hierarchy. Distinguish its message, cause, and suppressed exceptions.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

String getMessage();
Throwable getCause();
final Throwable[] getSuppressed();

java.lang.Throwable is the base class of Exception and Error. Its objects represent problems that can be thrown with throw and caught with catch.

Throwable.getMessage() returns a String message, which may be null. Throwable.getCause() returns the cause as a Throwable, or null if it is absent or unknown. Check for null before calling methods on the cause.

Throwable.getSuppressed() returns a Throwable[], empty when no exceptions were suppressed or suppression is disabled. A cause explains why a failure arose; a suppressed exception describes a separate failure, such as resource closing in try-with-resources. One object can contain both kinds of information.

Examples

public class Main {
    public static void main(String[] args) {
        Throwable cause = new IllegalArgumentException("invalid input");
        Throwable failure = new Exception("operation failed", cause);
        failure.addSuppressed(new Exception("cleanup failed"));

        System.out.println(failure.getMessage());
        System.out.println(failure.getCause().getMessage());
        for (Throwable suppressed : failure.getSuppressed()) {
            System.out.println(suppressed.getMessage());
        }
    }
}

Result

operation failed
invalid input
cleanup failed

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources