How to catch all checked exceptions (in a single block) in Java?
If I understood correctly, then you are almost there. Just catch RuntimeException. That will catch RuntimeException and everything under it in the hierarchy. Then a fallthrough for Exception, and you're covered:
try { transaction.commit(); } catch (RuntimeException e) { // Throw unchecked exception throw e; } catch (Exception e) { // Handle checked exception // ... }
Java 7
allows you such constructions:
try {
transaction.commit();
} catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException e ) {
// blablabla
}
UPD: I think, that there isn't nice and convenient way for doing it in earlier versions of Java. That is why developers of Java
language introduced such construction in Java 7
. So, you could devise your own approaches for Java 6
.