2011-02-08 30 views
0

我可以捕获java.lang.Exception而不是它的子类吗?我可以捕获java.lang.Exception而不是其具体的子类吗?

考虑这个塞纳里奥:

public class Tree { 
    public static Tree newInstance() throws NoWaterException, NoSoilException, NoSunshineException { 
     ... 
     return new Tree(); 
    } 
} 

当我想树一个例子,我可以这样做:

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 (NoSunshineException e) { 
     throw new TreePlantExcetpion("Cannot plant a tree since no sunshine", e); 
    } 
} 

但我也能做到这一点也可以使用:

public Tree plantTree() throws TreePlantExcetpion { 
    try { 
     ... 
     return Tree.newInstance(); 
    } catch (Exception e) { 
     throw new TreePlantExcetpion("Cannot plant a tree", e); 
    } 
} 

我更喜欢方法plantTree()的第二次执行,因为它更短且清晰r,在这种方法中,我不关心Exception的具体子类,我需要做的是将它包装在新的TreePlantExcetpion中并传递给它。所有的详细信息都不会丢失。我确信Tree.newInstance()方法不会抛出任何其他类型的异常(至少现在)。我可以这样做吗?

注意NoWaterExceptionNoSoilExceptionNoSunshineException不能成为TreePlantExcetpion子类。它们不在同一个继承层次结构中。

问题是,如果异常处理对于所有捕获到的异常都是相同的,那么我可以只抓住他们的超类,即java.lang.Exception而不是?

回答

2

让TreePlantException的NoWaterExceptionNoSoilExceptionNoSunshineException子类,你可以直接跳过整个try/catch语句,因为TreePlantException如抛出已声明。

+0

如果这些类不在继承层次结构中,该怎么办? – chance 2011-02-08 12:41:52

相关问题