异常对象上的 getMessage() 不提供空值



用这样的代码

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());
}

输出是这个

A) my cause
B) java.lang.Exception: my cause
C) my cause
D) my message
E) my cause
F) null
G) my cause

了解BF之间的区别

在这两种情况下,我都没有提供消息,但不同之处在于,在B情况下,不会强制null值。

似乎对于B情况,当未指定消息时,getMessage()方法提供格式className: cause.getMessage()但我除了有一个null值(就像F的情况一样)。

如果我在已创建的异常上getMessage调用仅提供cause而不是message的异常,有没有办法获取null值(如F)?

看看Exception的JavaDoc。对于只需要一个Throwable的构造函数:

构造具有指定原因和(cause==null ? null : cause.toString())详细信息消息的新异常(通常包含cause的类和详细信息消息)。此构造函数对于仅是其他可抛售对象的包装器的异常很有用(例如,PrivilegedActionException)。

因此,在 B 情况下,由于原因不为 null,因此您将获得cause.toString()的值作为容器异常的消息。

如果该构造函数用于创建异常,则当您捕获异常时,为时已晚 - 它已经具有上面指定的详细信息。您无法获取"null",因为详细信息消息不为 null。您可以将其与原因的toString()进行比较,并推断它应该是空的,但这是一个难题,从理论上讲,原因的信息可能会随着时间的推移而变化,并且在捕获时会有所不同。

基于@RealSkeptic回复,我创建了一个这样的方法

public static String getMessageOrNull(Throwable t) {
String message = t.getMessage();
if (t.getCause() != null && message.equals(t.getCause().toString())) {
message = null;
}
return message;
}

这可能不是最好的方法,但对于我的情况来说效果很好。

你可以简单地用同样的方式构建它,把它隐藏在一个静态方法中:

public static Exception getException(Throwable cause){
return new Exception(null, cause);
}

或者你定义自己的类,它将使用Exception(String, Throwable)构造函数,如

public MyExceptoin extends Exception{
public MyException(Throwable cause){
super(null, cause);
}
}

这将在以后使用起来更简单。

最新更新