Setting exception reason in java

I see how you catch an exception that I can print e.getCause(), although it is always null.

Do I need to install it somewhere, or is something missing that sets the cause to null?

+23
source share
4 answers

The exception has attributes messageand cause. A message is a description that tells the reader more or less exactly what went wrong. cause- this is something else: it is, if available, another (nested) Throwable.

This concept is often used if we use our own exceptions:

catch(IOException e) {
  throw new ApplicationException("Failed on reading file soandso", e);
  //                              ^ Message                        ^ Cause
}

Edit - in response to @ djangofans comment.

The standard is that a nested expression (reason) is printed with its stack trace.

public class Exceptions {
    public static void main(String[] args) {
        Exception r = new RuntimeException("Some message");
        throw new RuntimeException("Some other message", r);
    }
}

Exception in thread "main" java.lang.RuntimeException: Some other message
    at Exceptions.main(Exceptions.java:4)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.RuntimeException: Some message
    at Exceptions.main(Exceptions.java:3)
    ... 5 more

.

+49

class Exception , a cause Throwable. , .

+2

getCause. throwable null, . ( - , .)

Read the Java doc : getCause

+2
source

All Articles