Java 7 has eased some pain in the area of exception handling when the new try-with-resources and multi-catch syntaxes were introduced. The latter is very interesting from a syntax perspective because it is the only place in Java where formal union types are allowed, similar to what Ceylon offers. Remember, a union type A | B is a type has all the properties that both types share. For example:
try {
// ...
}
catch (SQLDataException | SQLWarning e) {
// Properties that both types share:
System.out.println(e.getSQLState());
}
The above can be quite useful in cases when we simply want to re-throw a variety of similar but disjoint exceptions in the same way. But often, we want do this:
// Some code
try {
}
// Rethrow
catch (OurException e) {
throw e;
}
// Wrap other types of exceptions in OurException
catch (Exception e) {
throw new OurException(e);
}
That’s quite a few lines of code for something that we do all the time and that could be called “rethrow-or-wrap” pattern. How about if we could rewrite the above as such:
// Some code
try {
}
// Re-throw exceptions of type OurException
// ... and wrap all other types in OurException
throws OurException;
Without a catch clause, this would be exactly the same as our previous example. Rethrow or wrap. Java is a language that heavily recycles keywords, so a dedicated keyword is out of question. throws would be a good keyword here as it is somewhat similar to the throws clause of a method signature, i.e. the throws clause of the try block.
If we only want to rethrow some exceptions and write tailor-made catch blocks for other types of exceptions, we could still do the same:
// Some code
try {
}
// Re-throw exceptions of type OurException
throws OurException
// But deal with all other types here
catch (Exception e) {
throw new OurException("Custom message", e);
}
Java should have a “rethrow Exception” statement.
What are your thoughts on this? Would such a syntax pull its own weight?