Switch expressions spec

Alex Buckley alex.buckley at oracle.com
Fri Mar 15 18:39:49 UTC 2019

// The mail below doesn't appear to have made it to the 
amber-spec-experts web archive, even though Manoj is a member of the list.

Hey Gavin,

In a switch expression, I believe it should be legal for every 
`case`/`default` arm to complete abruptly _for a reason other than a 
break with value_.

That is, a legal switch expression may have zero rules like `case a -> 
5;` (completes normally) or `case b -> { break 6; }` (completes abruptly 
for reason of break with value). Instead, it only has rules like `case c 
-> { throw new Exc(); }` or `case d -> throw new Exc();`, both of which 
complete abruptly for reason othan than break with value. (Extend to 
switch labeled statement groups.)

I suspect that the strong rule flagged by Manoj:

     It is a compile-time error if a switch expression has no result 

is trying to require a value `break` statement being present in every 
switch labeled block, because a rule earlier in 15.28.1 did not quite go 
that far:

     If the switch block consists of switch labeled rules, then any 
switch labeled block (14.11.1) must complete abruptly.


On 3/14/2019 4:14 PM, Manoj Palat wrote:
> Hi Alex, Gavin,
> One more clarification of the spec:
> Consider the following code:
> public class X {
> @SuppressWarnings("preview")
> public static int foo(int i) throws MyException {
> int v = switch (i) {
> default -> throw new MyException(); // error or no error?
> };
> return v;
> }
> public static void main(String argv[]) {
> try {
> System.out.println(X.foo(1));
> } catch (MyException e) {
> System.out.println("Exception thrown as expected");
> }
> }
> }
> class MyException extends Exception {
> private static final long serialVersionUID = 3461899582505930473L;
> }
> As per spec, JLS 15.28.1
> It is a compile-time error if a switch expression has no result expressions.
> ------------------------
> Throw statement is not a result expression and hence as per the spec we
> should be giving this error.
> Is this an omission in the spec? Should we be flagging an error?
> In Eclipse ECJ we are flagging an error but I observed javac does not -
> Want to get clarity on what does the spec mean.
> Regards,
> Manoj
> Eclipse Java Dev,
> IBM.

More information about the amber-spec-observers mailing list