首页 > 解决方案 > 为什么不能处理这个异常?

问题描述

假设我有这个例外:

class NoMoreCarrotsException extends Exception {}

这是一个已检查的异常,因此必须对其进行处理或声明。

假设我有这个方法:

private static void eatCarrot(){}
public void fails(){
   try{ 
      eatCarrot(); 
   }catch(NoMoreCarrotsException e){}
}

和这个:

public void works() throws NoMoreCarrotsException { 
    eatCarrot(); 
}

为什么第二个有效但第一个无效?该eatCarrot方法不会抛出异常,那么为什么我们可以声明/抛出它?

标签: javaexception

解决方案


您可以声明您的方法(works()在这种情况下)throws是一个异常,即使它没有抛出它。

原因是这将允许覆盖您的方法的子类抛出该异常(或该异常的任何子类)。

On the other hand, in a try-catch block, if you attempt to catch an exception that cannot be thrown by the try block, your catch block becomes dead code (i.e. code that can never be reached), and the compiler doesn't allow it.


推荐阅读