I have some code in a Java 8 app that throws N different exception classes which come from a separate library. There's currently a separate handler for each exception class despite them sharing some common code. I'd like to refactor this to avoid:
- Repeating the list of exception classes that have some commonality (for example using a switch,
instanceof
or casting) - Repeating calls to
someCommonCode
N times
class MyClass {
public void errorHandler(FirstException e) {
System.out.println("This error is not so bad");
}
public void errorHandler(SecondException e) {
System.out.println("This error is worse");
}
public void someMethod() {
try {
riskItAll();
} catch(FirstException | SecondException e) {
someCommonCode();
errorHandler(e);
moreCommonCode();
} catch(Exception e) {
uncommonCode();
}
}
}
So far, I've been stuck trying to find documentation / examples for dealing with multiple catch blocks in this way as I haven't found the term used to describe the type of e
inside such a block. There's no searchable terminology introduced on http://www.oracle.com/technetwork/articles/java/java7exceptions-486908.html
It could be a generic, but that would be surprising since you can't catch an instance of a type parameter.
The code snippet above does not build - the compiler error raised at errorHandler
is
error: no suitable method found for errorHandler(RuntimeException)
method MyClass.errorHandler(FirstException) is not applicable (argument mismatch; RuntimeException cannot be converted to FirstException)
method MyClass.errorHandler(SecondException) is not applicable (argument mismatch; RuntimeException cannot be converted to SecondException)