Java 处理已检查和未检查的异常?
我下面有一个类,其中有一个方法抛出Checked异常Java 处理已检查和未检查的异常?,java,exception,exception-handling,Java,Exception,Exception Handling,我下面有一个类,其中有一个方法抛出Checked异常 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 Sample{
public String getName() throws CustomException{
//Some code
//this method contacts some third party library and that can throw RunTimeExceptions
}
}
CustomException.java
现在在另一个类中,我需要调用上面的方法并处理异常
public String getResult() throws Exception{
try{
String result = sample.getName();
//some code
}catch(){
//here i need to handle exceptions
}
return result;
}
我的要求是:
sample.getName()
可以抛出CustomException,也可以抛出RuntimeException
在catch块中,我需要捕获异常。如果捕获的异常是RunTimeException
,那么我需要检查RunTimeException
是否是SomeOtherRunTimeException
的实例。如果是这样,我应该抛出null
如果RunTimeException
不是SomeOtherRunTimeException
的实例,那么我只需要重新显示相同的运行时异常
如果捕获的异常是CustomException
或任何其他选中的异常,那么我需要重新显示相同的异常。我怎样才能做到这一点?您可以简单地做到:
public String getResult() throws Exception {
String result = sample.getName(); // move this out of the try catch
try {
// some code
} catch (SomeOtherRunTimeException e) {
return null;
}
return result;
}
将传播所有其他已检查和未检查的异常。无需捕获和重新捕获。您可以这样做:
catch(RuntimeException r)
{
if(r instanceof SomeRunTimeException)
throw null;
else throw r;
}
catch(Exception e)
{
throw e;
}
注意:
Exception
捕获所有异常。这就是为什么它被放在底部。Erm,您不能抛出null
?您的意思是返回null
?@meriton您可以抛出null
。选中,因为null
不是可丢弃的Throwable
的实例,所以不能抛出或捕获它。当throw null
编译时,它实际上并没有抛出null
,而是抛出一个新的NullPointerException
(当我说“throw x”时,我的意思是规范所称的“突然完成,原因是带有值x的抛出”)
catch(RuntimeException r)
{
if(r instanceof SomeRunTimeException)
throw null;
else throw r;
}
catch(Exception e)
{
throw e;
}