Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 处理已检查和未检查的异常?_Java_Exception_Exception Handling - Fatal编程技术网

Java 处理已检查和未检查的异常?

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 现在在另一个类中,我需要调用上面的方法并处

我下面有一个类,其中有一个方法抛出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 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;
}