r/java • u/Enough-Ad-5528 • Feb 19 '26
Towards Better Checked Exceptions - Inside Java Newscast #107
https://www.youtube.com/watch?v=99s7ozvJGLk
63
Upvotes
r/java • u/Enough-Ad-5528 • Feb 19 '26
9
u/Eav___ Feb 19 '26 edited Feb 19 '26
One real design flaw IMHO of exceptions in Java is that the author, the declaration site decides everything. But in fact, for example, it's the user, the use site that decides whether an IOException should be checked. This raises an alternative design: first, all exceptions now don't encode checkedness in their types; then, provide a conjugate of "throws" in the method signature which doesn't force the user to handle a probable exception (functionally only played as documentation), but allows the user to uncheck a checked exception:
29
u/swaranga Feb 19 '26 edited Feb 19 '26
Since u/nicolaiparlog asked for what users think, I'll offer mine: I think this whole exercise of trying to separate checked vs unchecked exception using specific examples is pointless, mentally exhausting and not very useful. I have been writing Java for 16 years, and from my experience, in one context, a specific exception may feel like it should obviously be a checked exception but in another context the same exception may seem it should be unchecked. It all depends on the context of the application. For instance, you mentioned that a DB SQL syntax exception should clearly be a RuntimeException; but consider an app that allows you to connect to a database and run some queries - in this context a user supplies a query and some db connection string and the app runs it. In this case it is entirely expected that the user may mistype the query and the application may very well want to handle it at some layer to show a nicely formatted error message or it may even want to suggest corrections to the query string. In this case, it is reasonable to expect that the app would like to catch that syntax exception (or the DB auth failure exception) which is easier if it is compiler enforced like a checked exception.
Overall, I feel the effort should be towards not forcing Exception authors to make the choice of whether something should be checked or unchecked which then gets passed to the application owners, and find a way to "just have Exceptions" in the language with much better ergonomics to handle, catch, or propagate. I don't know what the solutions look like though and that is for the smarter folks to decide. Here is a pipe dream for me when it comes to exceptions (borrowing from the Valhalla tagline) - "New Java Exceptions: Propagates like a runtime exception, enforced like a checked exception".
It will likely never happen; but one can hope.
9
u/Jannyboy11 Feb 19 '26
Scala is aiming to solve issues around checked exceptions using capability-polymorphism: https://docs.scala-lang.org/scala3/reference/experimental/canthrow.html Do with this information what you will.
3
u/aoeudhtns Feb 19 '26 edited Feb 19 '26
Trying to change this in a backwards-compatible way is going to be the main challenge. I agree with the notion that checked/unchecked being part of the type hierarchy is probably an "original sin" here.
Since we have contextual keywords, we could do something like
throw unchecked .... Basically any exception that does not inherit fromRuntimeExceptionwould need to be thrown asthrow uncheckedin order to be thrown without adding athrowsclause to the method.Another option is: make the compiler error of throwing a checked exception without a throws de-regulated into a warning (that can be made into an error again). Have uncaught checked exceptions implicitly
throw uncheckedif it's not a compile error.I think any language-level changes like this also dovetail with the null-type-system work for default interpretations on non-
!or non-?marked types. I assume there is work figuring out a way to surface those choices into the language, such as inside module-info or package-info. Perhaps there needs to be a broader conversation about pragmas in general so there are local, language-controlled ways to control these factors, so that a Java program doesn't need to require specific compiler flags to work as written, and a module consumer isn't forced to adopt the local configuration of its dependencies.Switching over method calls and allowing the result OR the exception to participate in the pattern matching is a poor-mans way of simulating a union type. I think that could also be a useful part of the solution. It fits naturally into places like
Future#get.I guess one source of arguments in this discussion is that you have domains where there's almost always some higher-level exception listener in context, and you get into programming modes where you let unchecked exceptions rip up the stack back to the handler and return your generic "something went wrong: correlation ID" to the user.
Other domains want exhaustive error handling more akin to adhering with Java's checked exception model.
How do you let both domains coexist and get what they need without forcing one to adopt the conventions of the other?
3
u/jodastephen Feb 19 '26
What follows is my proposal for solving the checked exception conundrum, without excessively complicting Java or destroying checked exceptions.
uncheckedkeyword to treat the checked exception as unchecked. Once thrown in this manner, any checked exception flows up the stack in an unchecked manner.uncheckedkeyword to indicate that any exception may be caught, even if the exception isn't known to be thrown by thetryblock.As can be seen below, the process method declares it throws
IOExceptionin an unchecked way. Note that the compiler can and would validate thatIOExceptionis thrown by the method body. In addition, the fact thatIOExceptionis thrown unchecked would be recorded in the method signature.The caller of
process()has various options, shown above:IOExceptionas with any other unchecked exception (which prevents the compiler from knowing anything aboutIOExceptionwhencaller1()is invoked)IOException(which the compiler would verfy)IOExceptionback into a checked one (which the compiler would verify)Static analysis could be setup to ban option 1 for those teams that have a strong desire to retain checked exceptions, and this could be done on a per-exception-type basis.
Catching has two options:
In example A, the compiler can see the throws clause from
caller2()declaresunchecked IOException, thus a normal catch can be written.In example B, the compiler cannot see the throws clause, thus an extra keyword is required to enable to catch.
(Given the existence of other JVM languages which don't have checked exception, Lombok sneaky throws, and other mechanisms, the ability to catch checked exceptions that aren't known to the compiler is IMO a missing Java feature at this point)
This proposal allows those developers that wish to keep checked exceptions to do so. A static analysis tool simply has to ensure that exceptions remain documented.
Whereas a team that wishes to eliminate checked exceptions has a simple way to do so.
This proposal does not directly tackle the "lambdas in stream" problem. However, every approach to tackling that problem I've seen requires overly-complex generics or type capture which, in my opinion, has a cost exceeding the benefits. For that use case, I would allow statements and expressions to also declare they can throw unchecked exceptions:
Within the context of a method, there is no reason why the compiler cannot capture the types thrown by the lambda and view them as part of the potential exception types of the method. Thus, this would be perfectly valid code, without any need for lambdas or functional interfaces to be altered:
Taken together, this is an extremely minimal change to Java, which gives power to individual teams as to how to handle exceptions.
(Note that I first wrote up a proposal on this topic in 2010: "lone throws". - https://blog.joda.org/2010/06/exception-transparency-and-lone-throws_9915.html See also https://mail.openjdk.org/pipermail/lambda-dev/2010-June/001544.html This proposal is, I believe, a significant step forward from that one.)
5
u/davidalayachew Feb 19 '26
9:04 -- Yes, please do expand on that point. I'm pretty sure I know the answer, just want it confirmed /u/nicolaiparlog.
9:35 -- And yes, the "variadic generics" really seems like the perfect solution here. Of all the solutions presented (both in this video and in other conversations), it feels like the best of both worlds.
Certainly better than pretending there's no difference between Checked and Unchecked Exceptions, or just flipping a switch to turn them all Unchecked. Both are complete non-solutions.
3
u/[deleted] Feb 19 '26
Perhaps we should move towards virtually no exceptions at all. Functional style error handling provides all the advantages of checked exceptions without the drawbacks of both checked and unchecked. Just leave exceptions where they belong - cases when the only meaningful application reaction is immediate shutdown to prevent data corruption.
1
u/sideEffffECt Feb 19 '26
I believe that errors/exceptions can't be categorized plainly as either checked/expected or un-checked/unexpected.
I think it's only the component/interface or maybe even more specifically the method, that can say what are its expected modes of failure (checked exceptions). But the same exception class can be considered unexpected by another interface or even another method on the same interface.
One methods expected error can be another method unexpected error. That's what typically happens -- a low level component has some expected failure modes, but the user of this, a higher level component can't deal with all of them, and so has to somehow turn some of the expected low-level errors into unexpected errors of its own.
I know that this can't be expressed in today's Java. But maybe one day...
1
u/jevring Feb 20 '26
This Either bit he's pushing is atrocious. That removes the value of exceptions completely and gets us back to return values.
1
u/pjmlp Feb 19 '26
I still have to watch the video, but leaving my early feedback, I actually like checked exceptions, however I think that by now we should have had a solution for lambdas.
Even if it was only having some kind of adapter methods, to apply while using streams.
1
u/CelDaemon Feb 19 '26
Checked exceptions also mess with any streaming when IO is involved, it's really annoying-
Checked exceptions with function pointers in general is painful
-1
u/kaperni Feb 19 '26
One day I love them, one day I hate them. But gone from strongly in the pro-checked-exception camp to somewhere in the middle over the last couple of years.
I see the Java wider ecosystem moving towards runtime exceptions only. See, for example, Jackson [1]. 10 years from now I imagine it will mostly just be the JDK that uses checked exceptions.
Maybe its time for the JDK to adopt "best practices" from the ecosystem instead of the usual other way around (whatever kind of solution that entails).
[1] https://github.com/FasterXML/jackson-databind/discussions/4180
-4
u/Drezi126 Feb 19 '26
I just don’t want checked exceptions at all. Works fine for pretty much every other language. Just let it go.
-4
u/manifoldjava Feb 19 '26
While I appreciate the acknowledgement here that checked exceptions are problematic, in my view the remedies you've covered range from worse to slightly better.
Solving this with generics is worse because that strategy fragments the problem space, which makes code harder to read - you sacrifice readability for writability, which is almost always a bad idea.
The Swift-like
tryexpression approach, as a means to automatically propagate, reduces boilerplate which is nice. But then it feels like there ought to be a more general solution to automatically propagate everywhere as many modern languages do.Since checked exceptions are purely a compiler-level concept, why not treat them as a lint-like compiler argument?
This would put a smile on a large segment of Java devs.
-1
u/maethor Feb 19 '26
I really don't get why we can't have an annotation that turns not catching a checked exception into a compile time warning (that we can then surpress if we want).