java java中的throws语句是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12523633/
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
What does throws statement mean in java?
提问by fifteenthfret
Also, what does throws NumberFormatException, IOException
mean? I keep trying to use BufferedReader
by saying
还有,是什么throws NumberFormatException, IOException
意思?我一直在尝试使用BufferedReader
说
BufferedReader nerd = new BufferedReader(new InputStreamReader(System.in));
but BufferedReader
won't work unless throws NumberFormatException, IOException
is put in.
但BufferedReader
除非throws NumberFormatException, IOException
放入,否则将无法工作。
回答by arshajii
The throws
keyword indicates that a certain method can potentially "throw" a certain exception. You need to handle a possible IOException
(and possibly other exceptions) either with a try-catch
block or by adding throws IOException, (...)
to your method declaration. Something like this:
的throws
关键字表示一定的方法可以潜在地“抛”某种异常。您需要IOException
使用try-catch
块或通过添加throws IOException, (...)
到您的方法声明来处理可能的(以及可能的其他异常)。像这样的东西:
public void foo() throws IOException /* , AnotherException, ... */ {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
in.readLine();
// etc.
in.close();
}
public void foo() {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
in.readLine();
// etc.
in.close();
} catch (IOException e) {
// handle the exception
} /* catch (AnotherException e1) {...} ... */
}
回答by Vikdor
Throws clause is used to declare the exceptions that are not handled by a particular method and is an instruction to the callers to either handle these explicitly or rethrow them up in the call hierarchy.
Throws 子句用于声明未由特定方法处理的异常,并且是指示调用者显式处理这些异常或在调用层次结构中重新抛出它们的指令。
回答by md_5
The throws statement means that the function, may 'throw' an error. Ie spit out an error that will end the current method, and make the next 'try catch' block on the stack handle it.
throws 语句意味着该函数可能会“抛出”错误。即吐出一个错误,该错误将结束当前方法,并使堆栈上的下一个“try catch”块处理它。
In this case you can either add 'throws....' to the method declaration or you can do:
在这种情况下,您可以在方法声明中添加“throws....”,或者您可以执行以下操作:
try {
// code here
} catch (Exception ex) {
// what to do on error here
}
Read http://docs.oracle.com/javase/tutorial/essential/exceptions/for more info.
阅读http://docs.oracle.com/javase/tutorial/essential/exceptions/了解更多信息。