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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3843014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:37:44  来源:igfitidea点击:

Java: How to throw an Exception to the method caller inside a try catch body?

javaexception-handlingtry-catch

提问by Martijn Courteaux

When I have a method like this:

当我有这样的方法时:

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 */
    }
}

And when the IOException ("param is empty") is thrown, it is catched by the try-catchin that body. But this exception is meant for the caller of this method. How can I do this properly? Is there something "pure-Java" to do this or do I have to create an other type of Exception which is not an instance of IOException to avoid the try-catch body will handle it?

当抛出 IOException ("param is empty") 时,它会被该try-catch主体中的捕获。但是这个异常是针对这个方法的调用者的。我怎样才能正确地做到这一点?有什么“纯Java”可以做到这一点,还是我必须创建其他类型的异常,它不是 IOException 的实例,以避免 try-catch 主体处理它?

I know you would suggest to use a IllegalArgumentExceptionin this case. But this is a simplified example of my situation. In fact the Exception Ithrow is an IOException.

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

Thanks

谢谢

回答by Nikita Rybak

Making your own custom subclass of IOExceptionmight be a good idea. Not only to solve this problem, but sometimes it's a bit 'user-friendlier' for your API users.

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

Then you could ignore it in catch block (rethrow it immediately)

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

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

回答by andersoj

I think I'm confused by the specifics of your example -- why are you making the broad

我想我对你的例子的细节感到困惑——你为什么要广泛

} catch (Exception e) {

If that overly-generic catch clause wasn't there, your problem would go away.

如果那个过于通用的 catch 子句不存在,你的问题就会消失。

Did I misunderstand?

我误会了吗?

回答by tangens

You can check if your exception is an instance of IOExceptionand if it is, rethrow it.

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

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

回答by Codemwnci

You can catch it, and re-throw it, but the correct solution should be to be more selective of what you are catching in your catch statement....

你可以抓住它,然后重新抛出它,但正确的解决方案应该是在你的 catch 语句中更有选择性地捕捉到什么......

For example. In the code below, I am catching a FileNotFoundException, so the IOException is thrown back to the calling method.

例如。在下面的代码中,我捕获了 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 */
        }
    }

回答by Anon

I would create a subclass of IOException. This will let you use an instanceofcheck and rethrow.

我会创建一个IOException. 这将让您使用instanceof检查并重新抛出。

And there are very few cases where I use catch (Exception). It's almost always better to catch specific exceptions. The only reason not to is when you want to aggregate exceptions and rethrow (reflection operations are a common place to do this).

而且我在极少数情况下使用catch (Exception). 捕获特定异常几乎总是更好。不这样做的唯一原因是当您想要聚合异常并重新抛出时(反射操作是执行此操作的常见地方)。

回答by Colin Hebert

If IOExceptions are meant for the foo()caller, you can do this:

如果 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 */
    }

}

If your exception is the only one really needed to be rethrown, then create a new Subtype of IOException name it MyExceptionan try to catch MyExceptionto rethrow it.

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

Any pokemon exception handling is very ugly !

任何口袋妖怪异常处理都非常丑陋!