Hacker News new | ask | show | jobs
by pron 1560 days ago
To those perplexed by the behaviour of Java's Hello World, as Java is otherwise very careful with error handling, this is because System.out is a java.io.PrintStream, and that's its documented behaviour:[1]

> Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method.

So the correct Hello World would be:

    System.out.println("Hello World!");
    if (System.out.checkError()) throw new IOException();
While the behaviour of PrintStream cannot be changed (it goes back to Java 1.0, and I'm guessing that the intention was not to require handling exceptions when writing messages to the standard output), adding a method to obtain the underlying, unwrapped OutputStream might be an idea worth considering, as it would allow writing to the standard output just like to any file.

[1]: https://docs.oracle.com/en/java/javase/17/docs/api/java.base...

1 comments

It's a behavioural side-effect of checked exceptions. Because IOException is a checked exception, throwing it for console output would cause a lot of pain for printf debugging.
Well, Java has since introduced RuntimeIOException, which could be used in cases where an IO exception is unexpected, so we could introduce a new class, say, ErrorCheckingPrintStream, and add the method `ErrorCheckingPrintStream withErrorChecks()` to PrintStream if it's considered sufficiently worthwhile. So you could have:

    System.out.withErrorChecks().println("Hello World!);
But we can't change the behaviour of the existing PrintStream.
I think you mean UncheckedIOException - https://docs.oracle.com/javase/8/docs/api/java/io/UncheckedI...

RuntimeIOException from Jira has an amusing (and incorrect, IMO) message:

https://docs.atlassian.com/software/jira/docs/api/7.6.1/com/...

    > An IOException was encountered and the stupid programmer didn't know 
    > how to recover, so this got thrown instead.
It's a misguided doc comment because "recovering" from error is usually the wrong thing to do - usually the right thing is to abort whatever action is taking place, whether it's a request handler, event loop or standalone program. Situations like low disk space, incorrect file permissions, missing files and so on usually can't be recovered deep in the stack or without manual intervention.
Right, UncheckedIOException. Sorry.
This interesting me because it shows that they had experience really early on in Java development that checked exceptions caused pain, and rather than realize that something was wrong with the design they started swallowing and ignore errors.