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

Mar*_*aux 5 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 */
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Nik*_*bak 7

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

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

} catch (FooIOException e) {
    throw e;
} catch (Exception e) {
    /* handle some possible errors of of the IOoperations */
}
Run Code Online (Sandbox Code Playgroud)