given the code
Future<Box> f = ...
switch (f.get()) {
case Box(String s) when isGoodString(s) -> score(100);
case Box(String s) -> score(50);
case null -> score(0);
case throws CancellationException ce -> ...ce...
case throws ExecutionException ee -> ...ee...
case throws InterruptedException ie -> ...ie...
};
I read the above as"if f.get() is a Box(...) then ..."
"if f.get() is null then ..."
"if f.get() throws ExecutionException then ..."
People don't have problem reading try/catch, are used to it, it's already there, semantics match - why complicate things?
Case is better read as "captures ... [when ...]" and "case catch" simply means capturing an exception - the same way as try/catch does it.
If you flip it around - if somebody would do an experiment where they'd ask 100 developers to imagine that java supports catching exceptions in switch statements my bet is that almost all, if not all would write it as "case catch ...".
And there is really nothing fundamentally wrong with that. You can't catch catch handler, you can only catch an exception.
We don't have a problem reading try/catch because it comes from an era when Java was more procedural and less functional. "case throws" makes more sense in the functional-style Java era. (Well, makes more sense to me at least)
EDIT: To clarify "catch" is a verb and contains a block of executable statements. "case throws" maps to an expression (because I assume most people writing new code that uses this will be using switch expressions, not switch statements) In this context, "case throws" is a better choice because you are talking about the _expression_ inside the "switch".
switch (f.get()) {
case Box(String s) when isGoodString(s) -> score(100);
catch InterruptedException ie -> ...ie...
};
Current try/catch gymnastics are laborious, requiring blocks making usage unwieldy in otherwise-one-line lambdas. Requiring "case throws" is yet more useless syntax inflation. It would be nice to keep things streamlined this once.My kneejerk reaction would be to prefer something like "threw" in place of "throws", but I'm sure there's a reason not to.
Language designers try to avoid adding new keywords if at all possible, especially ones that are short and common. Doing so requires either breaking thousands of projects and APIs or adding a bunch of complexity to the grammar and syntax highlighting tooling (so threw is only a keyword in some contexts but not others).
I would even accept just "catch", such that a switch can hold a mix of "case" and "catch" clauses, which would be most natural.
"throws" is way too close to an action of throwing.