Exceptions, "catch", "switch" and "instance of"

Fred Toussi fredt at users.sourceforge.net
Thu Sep 17 15:36:55 UTC 2020


The preview extension to the switch statement is interesting, although it has a niche usage area.  But if it is extended to cover exception handling, it would make a significant improvement.

I have copied below an example used by Brian Goetz in an article on InfoQ:

try {
    V v = future.get();
    // handle normal completion
}
catch (TimeoutException e) {
    // handle timeout
}
catch (InterruptedException e) {
    // handle cancelation
}
catch (ExecutionException e) {
    Throwable cause = e.getCause();
    // handle task failure
}

The pattern above is a form of "switch" on the type of the caught exception. It can get error prone if other throwables are added to the list in the wrong order. No validation.

With a "switch" applied without extra ceremony, the order of the "case" blocks can be validated. I propose the syntax below to be added to the mix and tested as a preview feature.

try {
    V v = future.get();
    // handle normal completion
} catch switch(e) {
    case TimeoutException -> {  
    // handle timeout
    }
    case InterruptedException -> {
    // handle cancelation
    }
    catch ExecutionException -> { // there is no need for a new variable, e is now an instance of ExecutionExcption
    Throwable cause = e.getCause();
    // handle task failure
    }
}



More information about the amber-spec-observers mailing list