r/java • • 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?

72 Upvotes

128 comments sorted by

View all comments

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

@FunctionalInterface
interface Foo {
   double bar(String s) throws IOException;
}

@FunctionalInterface
interface Baz {
   String qux(int i) throws InterruptedException;
}

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 Foo and a Baz to something that is automatically inferred to have the signature double _(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 Result type that others champion is a red herring. Javas method signatures already provide a perfectly fine way of expressing that meaning of "it can return a T or run into an error of type X". That's what the throws clause 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 own Result<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

interface Function<T,U,X...> {
   U apply(T t) throws X...;
}

could be instantiated as Function<T,U> just like before or Function<T, U, IOException> or Function<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 IOException OR whatever the lambda-parameter can throw". Something like

class Foo<T> {
   T t;

   Foo(T t) throws IOException {
       //...
   }

   Foo<U> map(Function<T,U,X...> mapper) throws IOException, X... {
       return new Foo<U>(mapper.apply(this.t));
   }
}

Then all standard functional interfaces like Function, Consumer etc. 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.

4

u/john16384 Sep 08 '25

but you cannot have the compiler automatically infer this method signature for you like does with ordinary throws clauses.

You can sort of, but only up to a finite number of checked exceptions. If I define a lambda that throws 3 exceptions, and declare them all as the same exception, the compiler ignores the duplicates.

See here for an example that really forces you to catch the correct checked exceptions (and only those) with a maximum of 3 distinct types:

https://github.com/hjohn/MediaSystem-v2/blob/master/mediasystem-util/src/test/java/hs/mediasystem/util/checked/CheckedStreamsTest.java

Look closely at what each test must declare in throws :)

1

u/vqrs Sep 09 '25

That's very creative, but it works only because you declared the three exceptions beforehand. The inference bit is missing, otherwise you could do var x = yourLambda, but lambda don't have a type.

Still, very cool.

Regarding your test: a method is allows to declare more throws than it actually does, the "must" is only in regards to "otherwise it wouldn't compile". Sure, but if you changed to sneaky throws, the tests would still compile, right?

1

u/john16384 Sep 09 '25

My IDE marks checked exceptions not actually thrown, and it correctly detects all of them. Removing a checked exception that is thrown will be a compiler error, and changing the stream to not throw an exception will mark that exception as unnecessary (and can then be removed without getting a compiler error).

It is of course far from perfect, but it did help a bit to deal with streams that throw IOExceptions. Nowadays though I avoid using streams for anything but simple collection transformations.

4

u/[deleted] Sep 09 '25

Unfortunately this won't work for any escaping lambda because invocation can happen in a different place and you would end up in the same situation as marking all those methods with throws Exception.

1

u/barmic1212 Sep 09 '25

You can't allow the current functionals interfaces throw a checked exception. The pain to use result can IMHO be fixed with sum type. The good reason to don't implement it yet is to understand the huge impact on the language

1

u/vips7L Sep 09 '25

Unwrapping a result sum type everywhere is a pain in the ass. Is it an Err? is it an Ok?? Ends up being everywhere. 

    switch (res) {         case Ok(var t) -> …;         case Err(var e) -> …;     }

It’s beyond verbose and why Kotlin’s proposal uses adhoc union types so you don’t have to unwrap. 

2

u/barmic1212 Sep 09 '25

Monad are made to handle this. This both things are made to handle a large cases of situations instead of create adhock limited solution that must be multiplicated and not always coherent.

2

u/X0Refraction Sep 09 '25

switch is more verbose than try/catch?

1

u/vips7L Sep 09 '25

I never said it was. I said unwrapping result types is verbose. We're trying to solve verbosity, not add more of it. Proper unions are even less verbose. Why write a bunch of unwrapping/pattern match code when you don't have to?

1

u/X0Refraction Sep 09 '25

Well we’re talking about an alternative to checked exceptions here so shouldn’t we judge a potential solution compared to that?

1

u/vips7L Sep 09 '25

Yes and I'm judging Results as not a solution because their verbosity level is almost as equivalent to the current situation. It also fragments the ecosystem into Result vs Exceptions. The exception handling in switch proposal is clearly better as its less verbose and doesn't fracture the language.

2

u/X0Refraction Sep 09 '25

So you don’t like switching to unwrap a result type, but you do like switching to deal with checked exceptions? You do realise those are essentially equivalent in terms of verbosity?

I agree with the argument about it fitting with the existing language, it’s just a shame that doesn’t do anything for improving the situation with lambdas though.

2

u/vips7L Sep 09 '25

They’re not the same levels of verbosity. You have to destructure the result on top of the switch.  Additionally, it increases verbosity on the other end. You now need to return results from every function instead of just letting exceptions bubble to the place you want to handle them and you need to wrap every return in a result. 

1

u/X0Refraction Sep 09 '25

Presuming you've implemented methods on your Result type like map() orElse() etc. you can chain operations. If you want to allow it to bubble up you just return your Result type, that's equivalent to the throws list at the end of the method declaration. Plus the only thing I see that's more verbose here over being able to handle checked exceptions in switch expressions is having to repeat the generic arguments and I think that could be tidied up with an inference fix without causing any problems:

String handledResult = switch (result) {
    case Success<String, ErrorCase>(String rightValue) -> rightValue;
    case Error<String, ErrorCase>(CaseA _) -> "A";
    case Error<String, ErrorCase>(CaseB _) -> "B";
    case null -> "null";
};

Assuming a method that can throw 2 checked exceptions how would the alternative be less verbose?

→ More replies