Expression switch exception naming

Brian Goetz brian.goetz at oracle.com
Wed Mar 28 19:48:58 UTC 2018



> I have been figuring that if the client /has/ a reasonable way to 
> handle unknown values then it will probably go ahead and do that (with 
> a `default`).

I think that's a fair assumption for your codebase, but not in general.  
Developers will surely do this:

     x = switch (trafficLight) {
         case RED -> ...
         case YELLOW -> ...
         case GREEN -> ...
     }

and leave out a default because they can.  So they get a default 
default, one that throws.  No problem.

The only question here is: what to throw.  My argument is that Error is 
just too strong an indicator.  (It's like using fatal as your logging 
level for everything; it would be more useful to use warning for things 
that aren't fatal).

 From the Error doc:

An|Error|is a subclass of|Throwable|that indicates serious problems that 
a reasonable application should not try to catch. Most such errors are 
abnormal conditions.

Serious problems mean that underlying VM mechanism have failed. 
Encountering an unexpected input is not in this category.  Sure, it 
deserves an exception, but its not an ICCE.

> Therefore I assumed that what we're talking about in this conversation 
> is the/other/ kind, where there is nothing safe they can do - for 
> example if I wrote a method that displays a time interval as "10 ns" 
> or "20 s", I may not find it acceptable for me to start displaying "30 
> <unknown unit>" once I get handed TimeUnit.DAYS. My code is broken 
> either way. If a constant is added, I need to react to that, just like 
> I do with a new interface method. What does it really mean to say that 
> this client "brings a piece of the responsibility" if it doesn't 
> really have a choice?

It's not unlike this:

     AnEnum e = f(...);
     switch (e) {
         ...
     }

and not being prepared for a null.  You'll get an NPE.  The local code 
isn't expected to deal with it, but somewhere up the stack, someone is 
prepared to deal with it, discard the offending incoming work item, log 
what happened, and re-enter the work loop.

> So, I'm not quite yet following why the binary/source compatibility 
> distinction, or the opt-in distinction, really makes all the 
> difference here.

Some incompatibilities are more of a fire drill than others.  Binary 
incompatibilities (e.g., removing a method) are harder to recover from 
than unexpected inputs.  Further, while there may be no good _local_ 
recover for an unexpected input, there often is a reasonable global 
recovery.  Error means "fire drill".  I claim this doesn't rise to the 
level of Error; it's more like NumberFormatException or NPE or 
ClassCastException.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20180328/af15348c/attachment.html>


More information about the amber-spec-experts mailing list