何时在Java方法声明中使用throws? [英] When to use throws in a Java method declaration?

查看:137
本文介绍了何时在Java方法声明中使用throws?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我以为我对Java中的异常处理有了很好的基础了解,但是最近我读了一些让我有些混乱和疑惑的代码。我主要怀疑,我想在这里解决的是什么时候应该使用一个Java方法声明如下:

So I thought I had a good basic understanding of exception-handling in Java, but I was recently reading some code that gave me some confusion and doubts. My main doubt that I want to address here is when should a person use throws in a Java method declaration like the following:

    public void method() throws SomeException
    {
         // method body here
    }

从阅读一些类似的帖子我收集, throws 被用作一种声明,可以在执行该方法时抛出SomeException

From reading some similar posts I gather that throws is used as a sort of declaration that SomeException could be thrown during the execution of the method.

我的混乱来自一些如下所示的代码:

My confusion comes from some code that looked like this:

     public void method() throws IOException
     {
          try
          {
               BufferedReader br = new BufferedReader(new FileReader("file.txt"));
          }
          catch(IOException e)
          {
               System.out.println(e.getMessage());
          }
     }

是否有任何理由要使用 throws 在这个例子中?看来,如果你只是做一些像EXException这样的基本的异常处理,你只需要try / catch块就可以了。

Is there any reason that you would want to use a throws in this example? It seems that if you are just doing basic exception-handling of something like an IOException that you would simply need the try/catch block and that's it.

推荐答案

如果你正在捕获一个异常类型,你不需要抛出它,除非你要重新抛出它。在您发布的示例中,开发人员应该已经完成​​了一个或另一个,而不是两个。

If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

通常,如果您不执行任何异常操作,则不应该抓住它。

Typically, if you are not going to do anything with the exception, you should not catch it.

最危险的事情是抓住一个例外,不要做任何事情。

The most dangerous thing you can do is catch an exception and not do anything with it.

讨论什么时候适合抛出异常在这里

A good discussion of when it is appropriate to throw exceptions is here

何时抛出异常?

这篇关于何时在Java方法声明中使用throws?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆