【发布时间】:2013-12-19 10:11:48
【问题描述】:
我在下面的课程中使用了一种引发 Checked Exception 的方法。
public class Sample{
public String getName() throws CustomException{
//Some code
//this method contacts some third party library and that can throw RunTimeExceptions
}
}
CustomException.java
public class CustomException Extends Exception{
//Some code
}
现在在另一个类中,我需要调用上面的方法并处理异常。
public String getResult() throws Exception{
try{
String result = sample.getName();
//some code
}catch(){
//here i need to handle exceptions
}
return result;
}
我的要求是:
sample.getName() 可以抛出 CustomException,也可以抛出 RunTimeExceptions。
在 catch 块中,我需要捕获异常。如果捕获的异常是RunTimeException,那么我需要检查RunTimeException 是否是SomeOtherRunTimeException 的一个实例。如果是这样,我应该抛出 null。
如果RunTimeException 不是SomeOtherRunTimeException 的实例,那么我只需要重新抛出相同的运行时异常。
如果捕获的异常是CustomException 或任何其他检查异常,那么我需要重新抛出相同的异常。我该怎么做?
【问题讨论】:
-
呃,你不能扔
null?你的意思是返回null? -
@meriton 你可以
throw null。检查this -
因为
null不是Throwable的实例,所以它不能被抛出或捕获。虽然throw null编译,但它实际上并没有抛出null,而是一个新的NullPointerException(当我说“抛出x”时,我的意思是规范所说的“突然完成,原因是价值x 的抛出” .)
标签: java exception exception-handling