【问题标题】:Handling Checked and unchecked exceptions?处理已检查和未检查的异常?
【发布时间】: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


【解决方案1】:

你可以这样做:

catch(RuntimeException r)
{
     if(r instanceof SomeRunTimeException)
       throw null; 
       else throw r;
}
catch(Exception e) 
{
     throw e;
}

注意:Exception 捕获所有异常。这就是为什么它被放置在底部。

【讨论】:

    【解决方案2】:

    你可以这样做:

    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;
    }
    

    将传播所有其他已检查和未检查的异常。无需接住再扔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多