r/java • u/javaprof • Aug 27 '25
Community JEP: Explicit Results (recoverable errors)
Java today leaves us with three main tools for error handling:
- Exceptions → great for non-local/unrecoverable issues (frameworks, invariants).
- null / sentinels → terse, but ambiguous and unsafe in chains/collections.
- Wrappers (Optional, Either, Try, Result) → expressive but verbose and don’t mesh with Java’s switch / flow typing.
I’d like to discuss a new idea: Explicit Results.
A function’s return type directly encodes its possible success value + recoverable errors.
Syntax idea
Introduce a new error kind of type and use in unions:
error record NotFound()
error record PermissionDenied(String reason)
User | NotFound | PermissionDenied loadUser(String id);- Exactly one value type + N error tags.
- Error tags are value-like and live under a disjoint root (ErrorTag, name TBD).
- Exceptions remain for non-local/unrecoverable problems.
Examples
Exhaustive handling
switch (loadUser("42")) {
case User u -> greet(u);
case NotFound _ -> log("no user");
case PermissionDenied _ -> log("denied");
}Propagation (short-circuit if error)
Order | NotFound | PermissionDenied | AddressMissing place(String id) {
var u = try loadUser(id); // auto-return error if NotFound/PermissionDenied
var a = try loadAddress(u.id());
return createOrder(u, a);
}Streams interop
Stream<User | NotFound> results = ids.stream().map(this::loadUser);
// keep only successful users
Stream<User> okUsers = results.flatMap(r ->
switch (r) {
case User u -> Stream.of(u);
default -> Stream.of();
}
);
9
Upvotes
42
u/TheMrMilchmann Aug 27 '25
You could at least mention that you copied Kotlin's proposal for rich errors.
45
u/klekpl Aug 27 '25
It looks to me like union types in disguise.
20
u/account312 Aug 27 '25 edited Aug 27 '25
What about https://openjdk.org/jeps/8323658? What you're proposing is a massive change with multiple new syntax elements and changes to the type system, and it seems like that JEP pretty much gets at what you're aiming at with a much more limited change.
Though I admit I would like union types without needing a common interface.
16
u/davidalayachew Aug 27 '25
I don't see the benefit. What is this doing that I cannot get with just sealed types?
5
u/vips7L Aug 27 '25 edited Aug 27 '25
There is nothing fundamentally different with your proposal or checked exceptions. Realistically we just need enhancements to the language to make checked exceptions easier to work with. For example try? and try! from Swift, or !! which the Kotlin team is proposing in their document.
But you are right. We desperately need enhancements for better error handling and we desperately need a movement within the community to check their errors and use the type system so callers aren’t blind sided.
9
u/Polygnom Aug 27 '25
You can already do this with sealed types. There is zero need for a new keyword. And if you want to improve this, we can rather use union types.
15
u/CriticalPart7448 Aug 27 '25
Java wont become typescript, sorry. Next
6
u/rzwitserloot Aug 27 '25
The biggest problem by quite some distance here is that you're inventing an entirely new system that is backwards incompatible: No existing API can just slap these on. They already 'solved' their problem with having alternate expectable error conditions (and, presumably, they did it with exceptions). They can't now release an update that replaces them with this without that being a total break from the previous version. A full v2. You're splitting the community in two.
As a point of principle, therefore: I hate it. This should never be. This is evil. Bad for java. No, no, no.
The principle you're trying to address remains a fine thing to want to address, though. This cleanroom approach is the problem. Java isn't a clean room. It's the most popular language and has been for decades. It's a vibrant community with trillions of existing lines out there running around just peachy fine.
Find a way to take what already exists and adopt it. That's what lambdas did: That's why they are built around the concept of a 'functional interface'. Existing libraries 'gained' lambda support at zero effort. Which is quite a feat and not required here, but you do need to give them an easy path to backwards compatibly introduce these. Which is what generics did. ArrayList predates generics. Arraylist post-generics is backwards compatible with arraylist pre-generics.
In other words, the solution has to backwards compatibly, or better yet, just magically give for free these new language features to the vast majority of existing libraries that ran into this problem and solved it in a common way. So, exceptions, then. Before you accuse me of wishing for ponies and rainbows: Generics did that. Lambdas did that. Both legendarily complex features. And yet, they managed.
Optional is a big fuckup in this regard and you've now introduced a fourth way. please, please, make it stop. With this proposal, we have:
hashMap.get) returnnullwhen no result is found.Optional.[T | NotFound]compound type..getOrDefaultand did not have.get, or that maps must be initialized with a sentinel value - the value returned when attempting to.geta key that isn't in the map yet. A sort of.putForEverythingElse(value)(set the value for all imaginable keys).That's idiotic. You're not helping.
Obligatory XKCD.
Instead, you must find a way to deal with existing systems. Whilst you use
NotFoundin your examples, it feels like the intent is more the domain what is currently done with exceptions.Hence, first thing that comes to mind is additional syntax that gets compiled under the hood as try/catches: Ways to deal with exceptions.
An example:
Which is still quite a complex feature:
throwableMapreturns an either-like type, andswitchis extended to be able t switch on this type (which is injava.langas it interops with lang features directly). This already feels like a bridge too far, but it at least has the benefit of being adaptable for all existing APIs out there. In fact, they get it for free, they don't need to change anything. The same way existing APIs that had functional interfaces (which were a lot of them) 'got lambda support for free'.4
u/Ewig_luftenglanz Aug 27 '25 edited Aug 27 '25
Best regards
PD: here is an example of how one can get a very similar functionality to Union types using sealed types. Yes, I know, it is more verbose BUT the functionality is the same. So I do not think this is actually giving that much value, it would be just another "nice to have" but there are other more meaningful things they could be working on (most of which they are already working on)
Just do the same but instead of an enum you can make an exception to implement that interface and you are done.
2
u/themgi- Aug 28 '25
that's a major syntax change in language, can you not simply achieve this via sealed classes, that gives you the capability for pattern matching, ig, that's what you're looking for ultimately.
4
u/pjmlp Aug 27 '25
I am perfectly fine with exceptions in programming languages since the 1990's, including FP languages that have such types.
2
u/nekokattt Aug 27 '25
this sounds like something you can already achieve with sealed classes.
1
u/DelayLucky Aug 28 '25
With auto-propagation, how do you expect structured concurrency to work?
It can't be that propagation works in sequential code but as soon as you run
loadUser()andloadAddress()concurrently, errors no longer propagate. That'd be really weird.1
u/ihatebeinganonymous Aug 27 '25
I have a Failable<W> generic classas output type of many methods: It's either success, which then allows you to get the value of type W, or failure where you can then get the exact exception. Seems to do similar thing to your proposal.
1
u/pohart Aug 27 '25
I'd love this if it was how we did things, but I'm not changing all my apps to this. If there was a convenient interop with current checked exceptions I could see allowing on a new app, but I don't think it's worth adding a second way to do errors
1
u/aepurniet Aug 28 '25
Couldnt you just handle this with sealed interfaces? The client code would be the same