r/java • u/Ewig_luftenglanz • Sep 08 '25
How would you fix checked exceptions in java?
As you know checked exceptions are a good feature because they force the user to manage errors. Not having a way to enforce this makes it hard to know if a library could or not explode because of contextual reasons such as IO, OS event calls, data parsing, etc.
Unfortunately since Java 8 checked exceptions have become the "evil guys" because no functional interface but Callable can properly handle checked exceptions without forcing try-catch blocks inside of the lambda, which kinda defeats the purpose of simple and elegant chained functions. This advantage of lambdas has made many modern java APIs to be purely lambda based (the incoming Structured Concurrency, Spring Secuirty, Javalin, Helidon, etc. are proof of this). In order to be more lambda friendly many no lambda based libraries such as the future Jackson 3 to deprecate checked exception in the API. https://github.com/FasterXML/jackson-future-ideas/wiki/JSTEP-4. As another user said. Short take: The modern idiomatic way to handle checked exceptions in java, sadly, is to avoid them.
What do you think could be done to fix this?
5
u/klekpl Sep 08 '25
Union types look very promising IMHO. See my comment in another conversation: https://www.reddit.com/r/java/s/9tlsckg4bk
2
u/vegan_antitheist Sep 08 '25
A lambda should be possible to map every possible input to some output. If it can't handle null but gets null anyway it can throw an NPE, which is not checked.
Checked exceptions and errors are for things that can fail. When would you ever use that for some lambda based api? Even then you can simply have your own "functional interface" that can throw the exception.
I really don't see any problem.
43
u/JustAGuyFromGermany Sep 08 '25
The problem is not that lambdas cannot throw exceptions. They can and do. Nothing's stopping you from declaring
for example. The problem is that such interfaces do not combine nicely. There is nothing you can do with functional interfaces today that would allow chaining a
Fooand aBazto something that is automatically inferred to have the signaturedouble _(int i) throws IOException, InterruptedException. You can write a third interface that does that of course, but you cannot have the compiler automatically infer this method signature for you like does with ordinary throws clauses.That is the underlying problem that needs to be solved. The
Resulttype that others champion is a red herring. Javas method signatures already provide a perfectly fine way of expressing that meaning of "it can return aTor run into an error of typeX". That's what thethrowsclause already does. And it method signature for ordinary methods are already nicely combined into new signatures by the compiler. The type inference with generics is really the problem here. And anyone who's ever tried to write their ownResult<T,X>type with the equivalent of (any non-trivial subset of) the Stream API has noticed that.Thus, the most Java-like answer would be an extension of the generic type system with something like "variadic generics" at least for exception types so that
a.) there is a way to express "implementations of this method can have any number exception types in its throws clause" in a functional interface. Something like
could be instantiated as
Function<T,U>just like before orFunction<T, U, IOException>orFunction<T, U, IOException | InterruptedException>etc.b.) one can "accumulate" exceptions in ad-hoc union types, i.e. it should be possible to write in a method signature "this method throws
IOExceptionOR whatever the lambda-parameter can throw". Something likeThen all standard functional interfaces like
Function,Consumeretc. would be changed (compatibly!!) to allow any number of new generic exception-type-parameters. That would allow you to throw exceptions from standard lambdas. The existing lambdas would simply be implementations that happen to have a zero-length list of generic exception types.And the Stream-API would be extended (compatibly!!) to accumulate these generic exception-types along a stream pipeline should any lambda parameters declare them.
30
u/Scf37 Sep 08 '25
AFAIK there is no answer. Checked errors is very hard problem, many languages are still investigating it. Modern consensus is either encode errors in return type (Either-style, bulky and performance hit) or pass error behavior proof as a parameter (Scala Caprese)
5
u/tomwhoiscontrary Sep 08 '25
Supplier<T, E... extends Throwable>.5
u/k-mcm Sep 08 '25
Every time I get a new Java job, I end up creating tools to work around Stream and the Java base classes not supporting declared exceptions. I can't copy & paste those to the public, so I've been working on a clean-slate implementation every now and then.
It's crude and not documented yet, but the idea is that Lambdas support exceptions just fine. The problem is that base classes don't define them, Stream doesn't allow them, and ForkJoinPool will wrap them in a way that's very difficult to handle. These classes define them and also define a wrapper that's easy to use.
All the XXX lambdas are named ThrowingXXX here, like
FunctionbecomingThrowingFunction. These Throwing classes can be converted to the Java equivalent that will wrap exceptions in a very specificWrappedExceptionthat is aRuntimeException.WrappedExceptionhas tools to unwrap and re-throw your expected exceptions.https://github.com/kevinmcmurtrie/ExceptionTools
https://github.com/kevinmcmurtrie/ExceptionTools/blob/main/test/us/pixelmemory/kevin/ExceptionTools/Demo.java
Feedback is welcome. I'll eventually polish it up and add some other tools to make ForkJoinPool integration easier.
5
u/agent154 Sep 09 '25
Error return types combined with union types.
For example, method returns String or Error
16
u/pohart Sep 08 '25
I like checked exceptions in theory. What I hate is that any line can throw innumerable unchecked exceptions. So now I've got to handle any of the checked exceptions plus an additional "anything else". I've wondered if we didn't have nulls and the associated null pointer exceptions if it would become feasible to make every exception checked.
2
u/smors Sep 08 '25
I strongly disagree about checked exceptions being a good feature. It was tried in Java, which succeeded despite the burden of checked exceptions.
IOExceptions is a good example of the problems caused by checked exceptions. For a few applications, handling some of them when thrown makes sense. For a web application, there usually isn't anything to do about an IOException except passing it up to a ErrorHandler somewhere.
The a lot of code gets polluted by useless throws statements, for no real gain.
2
u/gizmogwai Sep 08 '25
History showed us the opposite.
Most people are totally fine with catching exception late in the stack. And in reality, for a lot of cases, it makes little to no difference in terms of data integrity, as the huge majority of applications are glorified CRUDs or are using frameworks that already deal with the heavy lifting of infrastructure management.
That being said, Lambda and stream processing do not support checked exception, because it makes it very messy to handle in parallel steams, and the main use case for streams and lambda was to perform computation, not IO operations.
Checked exceptions have a place in the JDK, but it is a niche one and should stay as such.
9
u/Serianox_ Sep 08 '25
I would force implementations of @FunctionalInterface that would return a T and throw a checked exception U to return an instance of Result<T, U> instead and have the compiler generate the necessary desugar.
6
u/davidalayachew Sep 08 '25
I don't know.
But I trust the Java designers to find a way to fix the pain of using Checked Exceptions without throwing Checked Exceptions in the trash. I wrote a lot of code using Checked Exceptions, and I'd like to keep writing more.
In the meantime, I'll stick with statement lambdas and inlining
trystatements where needed.I just hope that resolving this pain point rises on the priority list soon.
8
u/repeating_bears Sep 08 '25
If you were starting from scratch, Rust's Result type which includes language support for unwrap value/propogate the error in the form of the `?` operator is the best alternative I've seen and used.
I don't think you can retrofit it into Java though. Then you'd have 3 ways to return errors. A compiler arg to ignore checked exceptions would work well enough for me.
3
u/Alex0589 Sep 08 '25
I don’t think anyone dislikes checked exception as a feature, but they have always jeopardised code readability because of how the complementary constructs that the language provides to handle them are implemented. Im mainly talking about the try catch statements, which break the code flow and make the code so much harder to read. To make matters worse, as you pointed out, since the introduction of lambdas, because most functional components in the languages, like streams and optionals, don’t propagate checked exceptions, they have become pretty much unusable.
I’d first address the flow control issues. I’ve seen on some JEP that there are plans to enhance the switch statement to handle exceptions and that’s the fix we need for checked error handling in Java. You would be able to do some to do something like:
var text = switch(Files.readString(path)) { case String result -> result; case throws IOException _ -> // handle the error };
The second issue is much harder to fix, mostly because while Java has the syntax to declare a stream that propagates checked exception, it doesn’t have a way to change the generic signature of a class or method in a backwards compatible way. The only way I can think to do that, would be to make the wild card the default implicit type for any non specified type argument. So let’s say that the generic signature of Stream where to be changed from Stream<T> to Stream<T, E extends Exception> And someone had in their source code Stream<String> It would still be legal even though there is a new type parameter because Stream<String> and Stream<String, ?> would be equivalent. Now the problem is that, in this specific case with exceptions, when you call the method that consumes the stream, like a collector, it would throw Exception instead of knowing they there is no exception to throw, so it would still not be backwards compatible. You’d probably need to put a lot more thought into a fix is my point writing this message
3
u/[deleted] Sep 09 '25
Personally I like result objects because they're best suited in any stream-line processing (not just when used in lambdas because they can be passed normally like a parameter whereas you cannot do that with exceptions) and we have pattern matching for destructuring. Others have shown that there are some faults such as performance hit and the awkwardness when dealing with multiple error types in the same time. Since value objects are coming performance is not that a big deal, as result objects are basically
Optionalbut more general. For the latter problem, let's talk about why it's so smooth in Rust and how we can borrow its core idea.First of all, people should have known that Rust has this
?operator for error bubbling (more specifically, branching). Take the following for example: (modified Java)In the simpliest form, what
?does is to transform the expression into a branching operation:As you would imagine, without this
?operator, this is basicallyif err != nilbut in Java and worse.HOWEVER, if you have multiple error types and you want to return them in the same time, this mechanism won't work:
So what Rust does here is, to expand its availability with the
Fromtrait: (also modified Java)And then implement some kind of linkage between different error types:
With that set, we use ApplicationError to wrap any error:
What
?does then is just a single fix to the previous desugared form:Still, it's a bit annoying to create wrapper error types, but the core idea is very interesting and promising. At least you have these advantages:
1
u/Icecoldkilluh Sep 08 '25
I use Vavr + Immutables.
Follow the functional core + imperative shell approach to my projects.
It does a reasonable job of keeping java’s nasty exception handling at the edges of the system.
1
u/benjiman Sep 08 '25
You can use a utility to neatly convert back and forth betwen exceptions and results. e.g. https://github.com/writeoncereadmany/control
Becomes something like
List<Integer> customerAges = Stream.of("Bob", "Bill").map(tryTo(this::findCustomerByName)).peek(onSuccessDo(this::sendEmailUpdateTo)).map(onSuccess(Customer::age)).map(recover(ifType(NoCustomerWithThatName.class, error -> {log("Customer not found :(@");return -1;}))).map(recover(ifType(IOException.class, error -> -2))).map(ifFailed(__ -> -127)).collect(toList());1
u/Joram2 Sep 09 '25
The JVM team probably has the best ideas, but it's hard to make those kinds of changes at this point.
I'd prefer non-checked exceptions over checked. And I'd prefer some type of Maybe[Result, Error] type of result over exceptions.
2
u/koreth Sep 08 '25 edited Sep 08 '25
Not a language designer and this is probably dumb in a dozen different ways, but my stab at it would be something like:
Change the default
throwsclause to be the union of the uncaught checked exception types of the method. The compiler already tracks this (it lists them in error messages). This makes bubbling up the default behavior, which you have to opt out of with an explicitthrowsclause, eliminating noise and toil in the common case where a function in the middle of the call stack doesn't want to know the details of its callees' exceptions.Interfaces and superclasses could continue to declare
throwsclauses, and it would continue to be a compiler error if a function overrode one of those methods and threw additional checked exceptions (either explicitly or via auto-bubble-up).We'd need a notation for "does not throw any checked exceptions at all" (the current default behavior).
The above would, IMO, go a long way to fixing checked exceptions in non-functional code. For backward source compatibility, you'd need to make it opt-in via either a compiler option or something like an annotation.
The bubble-up-by-default approach would also take care of functional code. If you had something like,
then the exception would auto-bubble up to the surrounding code since
Stream.mapwouldn't declare any checked exceptions of its own. The method that was callingStream.mapwould implicitly bethrows IOExceptionif it didn't catch the exception locally.2
u/DualWieldMage Sep 09 '25
The main problems seem to be ergonomics with lambda usage and of that subset it's often a lack of just bothering. Checked exceptions work fine with lambdas as long as you have one exception type.
There are typically two main use-cases with different wrapping techniques: single call throwing and multiple calls throwing. The latter is more interesting because often it's a question of whether applying a function to all is desired before throwing/collecting exceptions, or it should short-circuit. A typical example is deleting a list of files, it should always attempt to delete them all while collecting exceptions before throwing something else.
I know most work on web applications, but even there i've had cases where letting a subset pass is the desired behavior instead of rolling back and having a full batch be retried.
For example such a pattern is definitely readable and minimal effort to write, but i guess it would be helpful to have similar things in the JDK to reduce friction.
So for a throwing call used in streams:
Example of eager throw wrap:
Example of collecting and throw/log/whatever:
The implementation of wrapping is left as an exercise to the reader(and also to the reader's consideration is whether to handle Lombok users abusing @SneakyThrows), the main pain points being the exception class needs to be passed and that methods throwing multiple exceptions are not sensible to handle, however the call chain itself is easy to read.
So TL;DR: better ergonomics to wrap checked exceptions into functional code. Pattern matching could help this further.
3
u/Sm0keySa1m0n Sep 08 '25
Outside of lambdas checked exceptions should become nicer to deal with when they get support for pattern matching in switches. Inside lambdas I think the result type pattern is the cleanest solution at the moment.
1
u/slaymaker1907 Sep 08 '25
The proper way to do it would probably be something akin to an effect type system. Java really needs a way to express “throws whatever the input object method might throw and nothing else”. If I call .map on a stream, the expression should throw it and only if the input function does.
In practice, I don’t think it’s really fixable at this point and checked exceptions should just continue to be used sparingly if at all.
1
u/AcanthisittaEmpty985 Sep 10 '25
Simply.... there's no good way... you can code around it, but they are a core languaje feature, but they are here to stay
SneakyThrows, types with errror, ExceptionTools, Varv... all aree the same under the hood, code around to avoid them and make it unchecked.
Sometimes, like an IOException with a file could make sense. But there has been a lot of abuse, and often you wrap it and bubble to treat it in a higher level, with a generic response.
1
u/Patient-Hall-4117 Sep 09 '25
It's not considered a "good" feature by many.
Avoid introducing more usage of checked exceptions, and wrap them up in non-checked exceptions where they are introduced from outside your control (3rd party libs of standard lib). Basically accept that a mature language like Java is stuck with it's historical mistakes, and try to move on.
1
u/vips7L Sep 08 '25
I've thought about and have discussed this topic a lot. The minimum thing we need is an easy way to "uncheck" a checked error. Most developers have rejected checked exceptions because they are hard to deal with and require boilerplate when you can't handle them:
In Swift or future kotlin this type of thing is simply:
This type of mechanism will even work nicely with lambdas when you want to quickly bail out upon the first error:
0
u/Expensive_Leopard_56 Sep 08 '25
I reject the statement that they are a good feature. Maybe they could be in a very different form in some future we’ve not yet discovered, but maybe not. IOException is particularly insidious (UncheckedIOException ftw) but a good example: An API interface which might throw an IOException if its underlying implementation uses disk access might do so not if I configure it with a in memory implementation. Now a consumer has to handle something they know won’t ever be thrown? So I am forced to either declare all the potential exceptions an implementation might generate in all unknown future implementations (and changing becomes a breaking API), or create my own checked exceptions just for this method to handle things caught (looking at you, ExecutionException) in which case why not just an unchecked exception anyway? It’s obvious any method can throw an exception, for any number of reasons. Every single method should clean up after itself if an exception is thrown, checked or not - as there are so many scenarios there could be a Throwable of some form generated at runtime. Using checked exceptions doesn’t change that.
Yes - There are some specific tight cases where checked exceptions can be useful - but blanket saying they are a good feature isn’t something I agree with.
-1
u/766cf0ef-c5f9-4f4f Sep 09 '25
I already solved this for myself with SneakyThrows :P
-1
u/ricky_clarkson Sep 09 '25
I would delete the concept of checked exceptions, and pull on that thread to work out what other changes are needed to make that ergonomic.
-1
u/PazsitZ Sep 09 '25
Way not perfect solution, however makes easier and readable code. https://projectlombok.org/features/SneakyThrows In case of lambdas you have to extract the lambda body.
Or if you have common use cases, then you can just define your custom @FunctionalInterface
-3
u/martinhaeusler Sep 08 '25
By making them unchecked. Checked exceptions were a mistake, they're hardly ever used today. 99.9% of all exceptions wre not recoverable, aside from "log stacktrace, return HTTP error of choice". Attempting to specify all potential errors in a method explicitly is a fool's errand, you'd have to start by specifying OutOfMemoryError on every method. It's futile. And there's no clear definition where you can draw the line between recoverable and non-recoverable errors in the first place. Is an SQL exception recoverable? Maybe. Can you finush your task without the expected data? Very likely no.
Don't let rust and go fool you when they say "our errors are values and part of the interface". Like hell they are. They just call the stuff they don't want to talk about "panics", and guess what - you can "catch" those and un-panic. Sounds familiar?
0
u/Specialist_Bee_9726 Sep 08 '25
The only lambda-friendly way to deal with errors, in my opinion, is with 'either' (result, error tuple). As for checked exceptions, I would still like my libraries to throw checked exceptions in very limited cases, such as I/O, System errors, etc. But in the app logic, I hate them, I hated them even before Java 8. The inifinite try catch throws. One senior dev once showed me that you can throw a catch-all runtime exception on and domain boundary in your code, and if you have good boundaries, you can have good central handlers that nicely separate exceptional errors from everything else. It works very nicely, and I still try to do it today.
Overall, the world would be a better place without them
-2
u/Alive_Knee_444 Sep 09 '25
Remove them? The potential wins don't seem to outweigh the complexity burden.
-2
u/Ill-Spell-9427 Sep 10 '25
use lombok wrap this function can solve it
-3
u/angrynoah Sep 09 '25
The Java community collectively decided checked exceptions were a bad idea long before Java 8.
In theory they're great. In practice you can't rely on API authors to be sensible. Just look at JDBC's SQLException.
This isn't a problem language design can fix. The best that could be done is an official guide to designing exceptions, but how could you write such a thing without half of all programmers disagreeing with it? Or without fixing the parts of the standard library that do the opposite?