Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Throwable.getCause()

Returns the original exception wrapped by the current one.

Available since: Java 1.4

Syntax

public Throwable getCause()

Return value

ThrowableThe cause exception, or `null`.

Examples

Wrapping an exception while keeping the cause:

class ConfigException extends RuntimeException {
    ConfigException(String message, Throwable cause) {
        super(message, cause);
    }
}
 
int readPort(String value) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        throw new ConfigException("Bad port setting", e);
    }
}
 
void main() {
    try {
        readPort("80a");
    } catch (ConfigException e) {
        IO.println(e.getMessage());
        IO.println("cause: " + e.getCause());
    }
}

Output:

Bad port setting
cause: java.lang.NumberFormatException: For input string: "80a"

Notes

When you catch an exception and throw another, pass the original one to the constructor as the second argument — otherwise the information about the real cause is lost. printStackTrace() prints the whole chain of causes in Caused by: lines.

See also

  • Exception — The base class of exceptions a program can catch and handle.
  • UncheckedIOException — An unchecked wrapper around `IOException`, needed where checked exceptions are not allowed, such as in lambdas.
  • Throwable.getMessage() — Returns the message text of an exception.

In the tutorial

  • Custom exceptions — How to create your own exception class in Java — extending Exception or RuntimeException, the message, the cause and extra fields.

Thanks for reading!

Donate to the site — we work hard for you.