此代码抛出 NullPointerException 是标准行为吗?

发布于 2024-09-02 07:55:26 字数 295 浏览 5 评论 0原文

我在一些库代码中遇到了一个大问题,我将其归结为一条语句:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

浊酒尽余欢 2024-09-09 07:55:26

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 a null argument.

失而复得 2024-09-09 07:55:26

好的,在我的平台的 PrintStream.print 实现中发现了错误。我想我会跟开发商跟进。

public void print(String s) {
    // WHERE IS THE NULL CHECK??!
    for(int i=0;i<s.length();i++) {
        write(s.charAt(i));
    }
}

感谢您确认这确实是非标准行为。

Ok, found the error, in my platform's implementation of PrintStream.print. I guess I'll follow it up with the developers.

public void print(String s) {
    // WHERE IS THE NULL CHECK??!
    for(int i=0;i<s.length();i++) {
        write(s.charAt(i));
    }
}

Thanks for confirming that this is indeed non-standard behaviour.

娜些时光,永不杰束 2024-09-09 07:55:26

上面的内容不应该抛出异常。您确定没有类似以下内容:

System.out.println(a.b);

where a is null 吗?

或者,也许您的 System.out 已设置为 null(没有多少人意识到您可以设置 out/err 流)?

That above shouldn't throw an exception. Are you sure you don't have something like:

System.out.println(a.b);

where a is null ?

Alternatively, perhaps your System.out has been set to null (not many people realise that you can set the out/err streams)?

ヅ她的身影、若隐若现 2024-09-09 07:55:26

当我在标准桌面 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 prints null.

I think that throwing a NullPointerException is a bug in this case.

歌入人心 2024-09-09 07:55:26

我刚刚尝试在 sun 的 jdk 6 上运行它,效果很好。它按预期打印了 null。

I just tried running this on sun's jdk 6 and it worked just fine. It printed null as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文