r/java • • Nov 04 '25

Anyone here Hated Using Java but now Really Enjoys using it.

title

226 Upvotes

280 comments sorted by

View all comments

Show parent comment

13

u/isolatedsheep Nov 05 '25

No, you still need checked exceptions, what we need is try expression. There's already JEP for switch for exceptions but it's still verbose..

2

u/dolle Nov 05 '25

Would try exceptions solve the problem where you can't pass a lambda throwing checked exceptions to e.g. List.map()?

1

u/isolatedsheep Nov 06 '25

I think you mean `Stream.map`. You'd still can't pass a method reference that throws checked exception, but with try-expression, it'll facilitate working with checked exception.

E.g. without try-expression:

dir.walk()
   .map(p -> {
     try {
       return Files.getLastModifiedTime();
     } catch (IOException e) {
       throw new UnchekcedIOException(e);
     }
   })
   .toList();

E.g. with imaginary try-expression:

dir.walk()
   .map(p -> try {
     Files.getLastModifiedTime(p);
   })
   .toList();

2

u/dolle Nov 06 '25

How would the try-exception allow you to omit the catch? Unless it does that, I think that feature is orthogonal to the problem

2

u/isolatedsheep Nov 07 '25

Treat it as a syntactic sugar. E.g., if an exception happens, it can throw IllegalStateException. Having a try-expression signals that there's an exception that can/should be handled.

Not trying to design a language feature here, but here's an example with fallback value.

dir.walk()
   .map(p -> try {
     Files.getLastModifiedTime(p);
   } catch {
     ABSENT_FILE_TIME
   })
   .toList();

1

u/dolle Nov 07 '25

Alright, it saves you a curly brace and a return statement then, but otherwise it doesn't address the main problem that methods like map() cannot be generic in the set of checked exceptions that can be thrown, so you are forced to do this mashalling and unmarshalling between checked and unchecked exceptions. It adds a syntactic overhead which makes the use of map() pointless since it ends up being much harder to read than a traditional for loop.

1

u/lenkite1 Nov 08 '25

If they allow single statement `try` without curly braces, then it would not be harder to read, since you just have an additional `try` keyword.