Java 14中引入了新的JVM选项-XX:+ShowCodeDetailsInExceptionMessages
,以提供有用的NullPointerException消息 ,以准确显示在发生NullPointerException
时为空。 例如,考虑以下代码:
var name = library.get( "My Book" ).getAuthor().getName();
在Java 14之前,JVM仅打印导致NPE的方法,文件名和行号:
Exception in thread "main" Exception in thread java.lang.NullPointerException at Library.main(Library.java: 7 )
如您所知,此错误消息不是很有用,因为无法确定哪个变量实际上为空(不使用调试器)。 是图书馆,从图书馆归还的书还是书的作者?
在Java 14中,启用-XX:+ShowCodeDetailsInExceptionMessages
,您将获得以下消息:
Exception in thread "main" Exception in thread java.lang.NullPointerException: Cannot invoke "Author.getName()" because the return value of "Book.getAuthor()" is null at Library.main(Library.java: 7 )
异常消息将查明什么是null( Book.getAuthor()
),并显示由于此而无法执行的操作( Author.getName()
)。
翻译自: https://www.javacodegeeks.com/2020/05/java-14-helpful-nullpointerexception-messages.html