How do I catch all checked exceptions (in a single block) in Java?
Editor: this problem only involves Java 1.6 (and below) I'm sorry I didn't make it clear in the original post
The hierarchy here shows that Java exceptions are divided into two types: runtimeException instead of runtimeException:
I may have missed something, but wouldn't it be better to divide it into uncheckedexception and checkedexception? For example, the following statement has a considerable number of checked exceptions:
try { transaction.commit(); } catch (SecurityException e) { } catch (IllegalStateException e) { } catch (RollbackException e) { } catch (HeuristicMixedException e) { } catch (HeuristicRollbackException e) { } catch (SystemException e) { }
I'm just really interested in whether it succeeds or fails, so I want to handle checked exceptions as a group rather than unchecked exceptions, because it's not a good practice to catch unexpected errors So with this in mind, maybe I can do this:
try { transaction.commit(); } catch (Exception e) { if (e instanceof RuntimeException) { // Throw unchecked exception throw e; } // Handle checked exception // ... }
But it looks very bad Is there a better way?
Solution
If I understand correctly, then you are almost there Grab runtimeException This will capture the runtimeException and everything below it Then there is a vulnerability in exception, and you are covered:
try { transaction.commit(); } catch (RuntimeException e) { // Throw unchecked exception throw e; } catch (Exception e) { // Handle checked exception // ... }