何时在 Java 方法声明中使用 throws?

发布于 2024-10-06 21:26:13 字数 733 浏览 4 评论 0原文

所以我以为我对Java中的异常处理有了很好的基本了解,但我最近阅读的一些代码给了我一些困惑和疑问。我想在这里解决的主要疑问是,人们何时应该在 Java 方法声明中使用 throws,如下所示:

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

通过阅读一些类似的帖子,我发现 throws 被用作一种声明,< em>SomeException 在方法执行期间可能会抛出。

我的困惑来自于一些如下所示的代码:

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

您是否有任何理由希望在此示例中使用抛出?看起来,如果您只是对 IOException 之类的内容进行基本的异常处理,那么您只需要 try/catch 块即可。

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
    }

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());
          }
     }

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

波浪屿的海角声 2024-10-13 21:26:13

如果您正在捕获异常类型,则不需要抛出它,除非您要重新抛出它。在您发布的示例中,开发人员应该执行其中一项操作,而不是同时执行两项操作。

通常,如果您不打算对异常执行任何操作,则不应捕获它。

您能做的最危险的事情是捕获异常而不对其执行任何操作。

关于何时适合抛出异常的一个很好的讨论在这里

何时抛出异常?

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

When to throw an exception?

三生殊途 2024-10-13 21:26:13

仅当方法抛出已检查异常时,才需要在该方法上包含 throws 子句。如果该方法抛出运行时异常,则无需这样做。

有关检查与非检查异常的一些背景信息,请参阅此处:http://download. oracle.com/javase/tutorial/essential/exceptions/runtime.html

如果该方法捕获异常并在内部处理它(如第二个示例中所示),则无需包含 throws 子句。

You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.

See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html

If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.

李不 2024-10-13 21:26:13

您查看的代码并不理想。您应该:

  1. 捕获异常并处理它;
    在这种情况下,抛出
    不必要的。

  2. 删除try/catch;在这种情况下
    异常将由
    调用方法。

  3. 可能捕获异常
    执行一些操作然后重新抛出
    异常(不仅仅是消息)

The code that you looked at is not ideal. You should either:

  1. Catch the exception and handle it;
    in which case the throws is
    unnecesary.

  2. Remove the try/catch; in which case
    the Exception will be handled by a
    calling method.

  3. Catch the exception, possibly
    perform some action and then rethrow
    the exception (not just the message)

最偏执的依靠 2024-10-13 21:26:13

你是对的,在这个例子中, throws 是多余的。它可能是以前的一些实现留下的——也许异常最初是抛出的,而不是在 catch 块中捕获的。

You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.

神仙妹妹 2024-10-13 21:26:13

您发布的代码是错误的,如果捕获特定异常以处理 IOException 但抛出未捕获的异常,则应该抛出异常。

像这样的东西:

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

或者

public void method() {
   try {
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   } catch(IOException e) {
           System.out.println("Catching IOException");
           System.out.println(e.getMessage());
   } catch(Exception e) {
           System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
           System.out.println(e.getMessage());
   }
}

The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.

Something like:

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

or

public void method() {
   try {
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   } catch(IOException e) {
           System.out.println("Catching IOException");
           System.out.println(e.getMessage());
   } catch(Exception e) {
           System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
           System.out.println(e.getMessage());
   }
}
迷你仙 2024-10-13 21:26:13

在您给出的示例中,该方法永远不会抛出 IOException,因此声明是错误的(但有效)。我的猜测是原始方法抛出了 IOException,但随后进行了更新以处理其中的异常,但声明未更改。

In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.

自此以后,行同陌路 2024-10-13 21:26:13

这不是答案,而是评论,但我无法用格式化代码编写评论,所以这里是评论。

假设有

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

输出是

test
Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(MyClass.java:10)

该方法没有声明任何“抛出”异常,而是抛出它们!
技巧是抛出的异常是 RuntimeException(未经检查),不需要在方法上声明。
对于该方法的读者来说,这有点误导,因为她看到的只是“throw e;”。语句但没有声明 throws 异常

现在,如果我们有

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

我们必须在方法中声明“throws”异常,否则我们会得到编译器错误。

This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.

Lets say there is

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

The output is

test
Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(MyClass.java:10)

That method does not declare any "throws" Exceptions, but throws them!
The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method.
It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception

Now, if we have

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文