Reputation: 17794
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).
Upvotes: 23
Views: 11755
Reputation: 8774
You could try something like this, to basically catch everything and then re-throw the RuntimeException
if it is an instance of that class...
try {
methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
if (ex instanceof RuntimeException){
throw ex;
}
else {
throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
}
Seeing as though this would be messy to write over and over again (and bad for maintainability), I'd probably move the code into a different class, something like this...
public class CheckException {
public static void check(Exception ex, String message) throws Exception{
if (ex instanceof RuntimeException){
throw ex;
}
else {
throw new MyCustomInitializationException(message, ex);
}
}
}
And use it in your code like this...
try {
methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
CheckException.check(ex,"Class Resolver could not be initialized.");
}
Noting that we pass in the message
so that we can still customise our MyCustomInitializationException
.
Upvotes: 2
Reputation: 6921
If you can use Java 7, you can use a Multi-Catch:
try {
methodThrowingALotOfDifferentExceptions();
} catch(IOException|ClassCastException|... ex) {
throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
Upvotes: 15
Reputation: 149017
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);
}
Upvotes: 54