Is it possible to catch all exceptions except runtime exceptions?

Rasto picture Rasto · Nov 14, 2012 · Viewed 9.8k times · Source

I have a statement that throws a lot of checked exceptions. I can add all catch blocks for all of them like this:

try {
    methodThrowingALotOfDifferentExceptions();
} catch(IOException ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
} catch(ClassCastException ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
} catch...

I do not like this because they are all handled same way so there is kind of code duplication and also there is a lot of code to write. Instead could catch Exception:

try {
    methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}

That would be ok, except I want all runtime exceptions to be thrown away without being caught. Is there any solution to this? I was thinking that some clever generic declaration of the type of exception to be caught might do the trick (or maybe not).

Answer

bdoughan picture bdoughan · Nov 14, 2012

You could do the following:

try {
    methodThrowingALotOfDifferentExceptions();
} catch(RuntimeException ex) {
    throw ex;
} catch(Exception ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}