此代码抛出 NullPointerException 是标准行为吗?
我在一些库代码中遇到了一个大问题,我将其归结为一条语句:
System.out.println((String) null);
好吧,代码实际上看起来并不像那样,但它肯定会使用 null 调用 println
争论。这样做会导致我的整个应用程序抛出意外的 NullPointerException
。
一般来说,在这种情况下 println 是否应该抛出此异常,或者这是由于 out 实例的实现不佳而导致的非标准行为?
I've had a big problem in some library code, which I've pinned down to a single statement:
System.out.println((String) null);
Ok, the code doesn't actually look like that, but it certainly calls println
with a null argument. Doing this causes my whole applicaio to throw an unexpected NullPointerException
.
In general, should println
throw this exception under that circumstance, or is this non-standard behavior due to a poor implementation of the out
instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
sun的JVM简单地打印“null”。这是
PrintStream.print(String)
当给定null
参数时。The JVM of sun prints simply "null". This is the specified behavior of
PrintStream.print(String)
when given anull
argument.好的,在我的平台的
PrintStream.print
实现中发现了错误。我想我会跟开发商跟进。感谢您确认这确实是非标准行为。
Ok, found the error, in my platform's implementation of
PrintStream.print
. I guess I'll follow it up with the developers.Thanks for confirming that this is indeed non-standard behaviour.
上面的内容不应该抛出异常。您确定没有类似以下内容:
where
a
isnull
吗?或者,也许您的
System.out
已设置为 null(没有多少人意识到您可以设置out
/err
流)?That above shouldn't throw an exception. Are you sure you don't have something like:
where
a
isnull
?Alternatively, perhaps your
System.out
has been set to null (not many people realise that you can set theout
/err
streams)?当我在标准桌面 Java(Mac OS X 上的 Java SE 6 update 20)上尝试该行时,它不会抛出
NullPointerException
,它只是打印null
。我认为在这种情况下抛出 NullPointerException 是一个错误。
When I try that line on standard desktop Java (Java SE 6 update 20 on Mac OS X), it does not throw a
NullPointerException
, it just printsnull
.I think that throwing a
NullPointerException
is a bug in this case.我刚刚尝试在 sun 的 jdk 6 上运行它,效果很好。它按预期打印了 null。
I just tried running this on sun's jdk 6 and it worked just fine. It printed null as expected.