何时在 Java 方法声明中使用 throws?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4392446/
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
When to use throws in a Java method declaration?
提问by jbranchaud
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:
所以我以为我对Java中的异常处理有一个很好的基本了解,但我最近阅读了一些代码,让我有些困惑和疑惑。我想在这里解决的主要疑问是一个人何时应该在 Java 方法声明中使用 throws,如下所示:
public void method() throws SomeException
{
// method body here
}
From reading some similar posts I gather that throwsis used as a sort of declaration that SomeExceptioncould be thrown during the execution of the method.
通过阅读一些类似的帖子,我发现throws被用作一种声明,可以在方法执行期间抛出SomeException。
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 throwsin 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.
在这个例子中你有什么理由想要使用throws吗?似乎如果您只是对 IOException 之类的东西进行基本的异常处理,那么您只需要 try/catch 块就可以了。
采纳答案by hvgotcodes
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
关于何时适合抛出异常的一个很好的讨论是here
回答by RevBingo
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.
你是对的,在那个例子中throws
是多余的。它可能是从以前的一些实现中遗留下来的 - 也许异常最初是抛出而不是在 catch 块中捕获的。
回答by DaveJohnston
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.
在您给出的示例中,该方法永远不会抛出 IOException,因此声明是错误的(但有效)。我的猜测是原始方法抛出了 IOException,但它随后被更新以处理其中的异常,但声明没有改变。
回答by Shane Bell
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.
如果方法抛出已检查的异常,则只需在方法上包含 throws 子句。如果该方法抛出运行时异常,则无需这样做。
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
有关已检查与未检查异常的一些背景信息,请参见此处: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.
如果该方法捕获异常并在内部处理它(如第二个示例中所示),则无需包含 throws 子句。
回答by Damo
The code that you looked at is not ideal. You should either:
您查看的代码并不理想。你应该:
Catch the exception and handle it; in which case the
throws
is unnecesary.Remove the
try/catch
; in which case the Exception will be handled by a calling method.Catch the exception, possibly perform some action and then rethrow the exception (not just the message)
捕获异常并进行处理;在这种情况下
throws
是不必要的。删除
try/catch
; 在这种情况下,异常将由调用方法处理。捕获异常,可能执行一些操作然后重新抛出异常(不仅仅是消息)
回答by Ignacio lucatero
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.
您发布的代码是错误的,如果捕获特定异常以处理 IOException 但抛出未捕获的异常,则应抛出异常。
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());
}
}
}
回答by Αλ?κο?
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
该方法没有声明任何“抛出”异常,而是抛出它们!诀窍是抛出的异常是不需要在方法上声明的 RuntimeExceptions(未检查)。这对方法的读者来说有点误导,因为她看到的只是“throw e;”。声明但没有声明 throws 异常
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.
我们必须在方法中声明“throws”异常,否则我们会得到编译器错误。