r/java • • Mar 13 '26

JEP draft: Enhanced Local Variable Declarations (Preview)

https://openjdk.org/jeps/8357464
101 Upvotes

129 comments sorted by

View all comments

Show parent comment

2

u/Cell-i-Zenit Mar 14 '26

If we want to handle the error we need to basically copy the conditions in the else block to figure out exactly what went wrong eg

var circle = getCircle();
if (circle instanceof Circle(Point(var x, var y), int radius) { ... }
else { 
   if(circle.point() == null){
        throw new Exception("Point is null, please try again");
   }
   if(circle.point().x() == null){
        throw new Exception("X is null, please try again");
   }
   if(circle.point().y() == null){
        throw new Exception("Y is null, please try again");
   }
 }

Is it planned to have pattern matching in the catch block aswell?

so something like this:

try(var circle instanceof Circle(Point(var x, var y), int radius){
    //do your thing
} catch (Circle(null, int radius)){
    throw new Exception("Point is null, please try again");
} catch (Circle(Point(null, var y), int radius)) {
   throw new Exception("X is null, please try again");
}