问题
Is is possible to get a list (and catch) of the concrete exceptions that can be thrown by a method?
I am calling an API that uses a hierarchy of exceptions, but only declares the top level exception to a method. I want to be able to provide specific behaviour based on the exception, but I don't want to have to trace through the code to find the concrete exceptions that can be thrown.
There may be added complications that the API contains a number of layers separated by interfaces.
Simple example:
public interface MyInterface {
void doShakyStuff() throws Exception;
}
public class MyImpl implements MyInterface {
public void doShakyStuff() throws Exception{
double rand = Math.random();
if( rand > 0.1 ){
throw new IOException();
}
if( rand > 0.5 ){
throw new IllegalAccessException();
}
else{
throw new InterruptedException();
}
}
}
I want to be able to create the following try/catch as completely as possible and then tweak afterwards:
public class MyClass{
private MyInterface interface;
public void doStuff(){
try{
interface.doShakyStuff();
}catch(IOException e){
// ...
} catch( IllegalAccessException e){
// ...
} catch( InterruptedException e){
// ...
} catch(Exception e){
// something else
}
}
}
回答1:
The answer is: no.
The method declares what it throws. If it's only declaring a top-level exception (i.e. Exception
in your example) ... then that's all your IDE is going to know about / tell you to catch.
To find every subclass it could throw you'd have to look at the javadocs and/or code to find the subclasses or specific subclass being thrown that you're interested in.
Ultimately if you're using an API that's throwing a superclass of an exception, and there's some reason you need to know the concrete subclass ... it's a badly designed API. The point of throwing the superclass when writing an API is that there's only a single line of logic to deal with it regardless of which subclass is really being thrown.
回答2:
You can do this too.
try{
interface.doShakyStuff();
}catch(Exception e){
if(e instanceof IOException){
}
if( e instanceof IllegalAccessException ){
}
if( e instanceof InterruptedException ){
}
}
来源:https://stackoverflow.com/questions/21248921/how-to-get-a-list-of-concrete-exceptions-thrown-by-a-method-in-eclipse