With a code like this
public static void main(String[] args) {
Exception one = new Exception("my cause");
System.out.println("A) " + one.getMessage());
System.out.println();
Exception two = new Exception(one);
System.out.println("B) " + two.getMessage());
System.out.println("C) " + two.getCause().getMessage());
System.out.println();
Exception three = new Exception("my message", one);
System.out.println("D) " + three.getMessage());
System.out.println("E) " + three.getCause().getMessage());
System.out.println();
Exception fourth = new Exception(null, one);
System.out.println("F) " + fourth.getMessage());
System.out.println("G) " + fourth.getCause().getMessage());
}
The output is this one
A) my cause
B) java.lang.Exception: my cause
C) my cause
D) my message
E) my cause
F) null
G) my cause
See the difference between B and F
In both cases I did NOT provided a message, but the difference is that in the B case the null value is not forced.
It seems that for the B case, when a message is not specified, the getMessage() method provides the format
className: cause.getMessage()
But I would except to have a null value (as is for the F case).
Is there a way to get null value (like F) if I call the getMessage on an Exception that has been created providing only the cause and not the message?
Take a look at
Exception's JavaDoc. For the constructor that takes only aThrowable:So, in your B case, since the cause is not null, you get the value of
cause.toString()as the container exception's message.If that constructor was used to create the exception, then by the time you catch the exception, it's too late - it already has a detail message as specified above. You can't get the "null" as the detail message is not null. You can compare it to the cause's
toString()and deduce that it should have been null, but that's a kludge and theoretically, the cause's message could change over time and be different at the time of the catch.