java 报null_Java报异常时getMessage()方法返回null

有次在查看项目日志的时候发现getMessage()返回值是null,以为是代码写的有问题,后来发现空指针异常时返回值就是null,虽然问题原因找到,但是感觉在日志中单单输出null对我们查看日志不够友好,想找到一种更好的方式。

原因

翻阅了API后发现getMessage()是Throwable类提供的方法

getMessage

public String getMessage()

Returns the detail message string of this throwable.

Returns:

the detail message string of this Throwable instance (which may be null).

翻译过来的意思大概是:返回当前抛出的Trowable实例的详细信息(可能会是null)

从API中的说明可以得知,我们getMessage()得到的是null也不足为奇了,博主常遇见的null情况是空指针异常,具体是否还有其他的异常情况会得到null的也还不太清楚,看了其他博主的文章发现是会有其他异常也返回null的情况。

那么是否有更好的办法可以让我们知道输出错误是什么呢,答案是肯定的,在经过一番查找后发现有以下两种更好的方式:

使用Exception的printStackTrace()方法

使用Exception的toString()方法

区别

对比出现空指针异常时的区别

printStackTrace

当出现空指针异常时,会输出异常类型和异常代码所在的行数,在我们的代码量多起来以后,会出现一个类调用另一个类,报异常时会将每个报错的行都输出,当调用关系复杂起来的时候会输出一长串内容。

// 没有其他类调用时

java.lang.NullPointerException

at com.test.HelloWorld.main(HelloWorld.java:12)

// 其他类或方法调用时

java.lang.NullPointerException

at com.test.HelloWorld.test(HelloWorld.java:11)

at com.test.SecondTest.main(SecondTest.java:6)

toString

查看了jdk的源码后发现NullPointerException本身没有实现toString()函数,而是通过继承使用Throwable的toString()函数,该函数会先获取detailMessage的值(出现空指针异常时Throwable类的detailMessage为null,因此直接调用getMessage()方法会返回null),如果为空返回当前异常类名,否则返回detailMessage,所以即使是空指针异常也会返回java.lang.NullPointerException

/*** Returns a short description of this throwable.

* The result is the concatenation of:

*

*

the {@linkplainClass#getName() name} of the class of this object

*

": " (a colon and a space)

*

the result of invoking this object's {@link#getLocalizedMessage}

* method

*

* If {@codegetLocalizedMessage} returns {@codenull}, then just

* the class name is returned.

*

*@returna string representation of this throwable.*/

publicString toString() {

String s=getClass().getName();

String message=getLocalizedMessage();return (message != null) ? (s + ": " +message) : s;

}/*** Creates a localized description of this throwable.

* Subclasses may override this method in order to produce a

* locale-specific message. For subclasses that do not override this

* method, the default implementation returns the same result as

* {@codegetMessage()}.

*

*@returnThe localized description of this throwable.

*@sinceJDK1.1*/

publicString getLocalizedMessage() {returngetMessage();

}/*** Returns the detail message string of this throwable.

*

*@returnthe detail message string of this {@codeThrowable} instance

* (which may be {@codenull}).*/

publicString getMessage() {returndetailMessage;

}

结论

仅需要知道返回的异常类型时使用Exception的toString()方法,需要知道报错详情则使用Exception的printStackTrace()方法。

才疏学浅,如文中有错误,感谢大家指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值