Java:如何在try catch体内向方法调用者抛出异常?

时间:2010-10-01 20:59:07

标签: java exception-handling try-catch

当我有这样的方法时:

public static void foo(String param) throws IOException
{
    try
    {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

    } catch (Exception e) {
        /* handle some possible errors of of the IOoperations */
    }
}

当抛出IOException(“param为空”)时,它会被该主体中的try-catch捕获。但是此异常适用于此方法的调用者。我该怎么做呢?是否有“pure-Java”这样做或者我是否必须创建另一种类型的Exception,它不是IOException的实例以避免try-catch体将处理它?<​​/ p>

我知道您建议在这种情况下使用IllegalArgumentException。但这是我情况的简化示例。事实上,异常 I 抛出是一个IOException。

由于

6 个答案:

答案 0 :(得分:7)

制作自己的IOException自定义子类可能是一个好主意。不仅要解决这个问题,而且有时候对于API用户来说,它有点'用户友好'。

然后你可以在catch块中忽略它(立即重新抛出它)

} catch (FooIOException e) {
    throw e;
} catch (Exception e) {
    /* handle some possible errors of of the IOoperations */
}

答案 1 :(得分:3)

我觉得我对你的例子的细节感到困惑 - 你为什么要做广泛的

} catch (Exception e) {

如果那个过于通用的捕获条款不存在,你的问题就会消失。

我误解了吗?

答案 2 :(得分:2)

您可以检查您的异常是否是IOException的实例,如果是,请重新抛出它。

catch( Exception e ) {
  if( e instanceof IOException ) {
    throw (IOException)e;
  }
}

答案 3 :(得分:2)

你可以抓住它并重新抛出它,但正确的解决方案应该是更好地选择你在catch语句中捕获的内容....

例如。在下面的代码中,我捕获了一个FileNotFoundException,因此IOException被抛回到调用方法。

public static void foo(String param) throws IOException {
        try {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

        } catch (FileNotFoundException e) {
            /* handle some possible errors of of the IOoperations */
        }
    }

答案 4 :(得分:0)

我会创建IOException的子类。这将允许您使用instanceof检查并重新抛出。

我使用catch (Exception)的情况非常少。捕获特定异常几乎总是更好。唯一的原因是你想要聚合异常和重新抛出(反射操作是一个常见的地方)。

答案 5 :(得分:0)

如果IOExceptions适用于foo()调用方,则可以执行以下操作:

public static void foo(String param) throws IOException
{
    try
    {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        /* handle some possible errors of of the IOoperations */
    }

}

如果您的异常是唯一真正需要重新抛出的异常,那么创建一个新的IOException子类型名为MyException,尝试捕获MyException以重新抛出它。

任何口袋妖怪异常处理都非常难看!

相关问题