May I ever catch java.lang.Exception instead of its concrete subclasses?
May I ever catch java.lang.Exception instead of its subclasses?
Consider this senario:
public class Tree {
public static Tree newInstance() throws NoWaterException, NoSoilException, NoSunshineException {
...
return new Tree();
}
}
When I want to get an instance of Tree, I can do this:
public Tree plantTree() throws TreePlantExcetpion {
try {
...
return Tree.newInstance();
} catch (NoWaterException e) {
throw new TreePlantExcetpion("Cannot plant a tree since no water", e);
} catch (NoSoilException e) {
throw new TreePlantExcetpion("Cannot plant a tree since no soil", e);
} catch (N开发者_C百科oSunshineException e) {
throw new TreePlantExcetpion("Cannot plant a tree since no sunshine", e);
}
}
But I can also do this alternatively:
public Tree plantTree() throws TreePlantExcetpion {
try {
...
return Tree.newInstance();
} catch (Exception e) {
throw new TreePlantExcetpion("Cannot plant a tree", e);
}
}
I prefer to the second implementation of method plantTree
() since it is shorter and clearer, and in this method I don't care about the concrete subclasses of Exception
, what I need to do is to wrap it in a new TreePlantExcetpion
and pass it up. All the detailed information will not be lost. And I am sure that the Tree.newInstance() method will not throw any other type of exceptions (at least for now). May I do it in this way?
Note: NoWaterException
, NoSoilException
, NoSunshineException
cannot be subclasses of TreePlantExcetpion
. They are not in a same inheritance hierarchy.
The point is, if the exception handling is the same for all caught exceptions, may I just catch their super class, i.e. java.lang.Exception
instead?
Make NoWaterException
, NoSoilException
and NoSunshineException
subclasses of TreePlantException, and you could just skip the entire try/catch since TreePlantException
is already declared as thrown.
精彩评论