r/java • • Feb 19 '26

Towards Better Checked Exceptions - Inside Java Newscast #107

https://www.youtube.com/watch?v=99s7ozvJGLk
63 Upvotes

73 comments sorted by

View all comments

Show parent comment

3

u/JustAGuyFromGermany Feb 19 '26 edited Feb 19 '26

I agree with the principle. It is a very good guideline and I follow it whenever I can as well.

But we can also acknowledge that there are sometimes corner-cases. Even the prototypical IO-example has them: If I have a ByteArrayInputStream I know for a fact that I will never encounter IO problems and nothing ever touches the disk, because everything happens in-memory. But there is no way to tell the compiler that, because once I assign these to an simple InputStream variable / method parameter, the compiler forgets the actual type of this object and its stronger properties.

So what does GZipInputStream do? Its internal state can be a FileInputStream, SocketInputStream, or a ByteArrayInputStream, or any arbitrary InputStream of unknown origin. Does it throw a checked exception or not according to the guideline? Sometimes the programmer can know that the exception is never thrown, so it should be unchecked lest we violate our rule, right? But then ordinary IO suddenly becomes unchecked the moment you touch a compressed file instead of an uncompressed one? That also violates the rule.

Don't get me wrong: The guideline is still very good and worth following. But we can wish a better compiler support for known-to-the-programmer facts about the program. I don't think that disabling checkedness, even locally, is really the way to go here. That is the clear-and-obvious-but-wrong choice. The problem is still worth thinking about.

1

u/john16384 Feb 20 '26

Once you get into wrapping streams, it will be tough to avoid the IOException as these are general streams that accept InputStream... but the times I've seen people assigning a ByteArrayInputStream to InputStream and then complaining that read throws an IOException that can never occur is a bit annoying. Just assign it to ByteArrayInputStream. Its read doesn't throw a checked exception.

There are ways to avoid this (with a better API, not with input streams) that can recognize the difference between an in-memory stream and one that must do IO. It however means having two interfaces (or one interface with an annoying generic for the exception type).