Java 中 throw 和 throws 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25617680/
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
Difference between throw and throws in Java?
提问by user3527594
Can any one clearly state the difference between throw and throws in Java exception handling with an example? I have tried googling but couldn't arrive at a conclusion. Pls help
任何人都可以通过示例清楚地说明 Java 异常处理中 throw 和 throws 之间的区别吗?我试过谷歌搜索,但无法得出结论。请帮忙
采纳答案by Nirav Prajapati
throws
clause is used to declare an exception andthrow
keyword is used to throw an exception explicitly.If we see syntax wise then
throw
is followed by an instance variable andthrows
is followed by exception class names.The keyword
throw
is used inside method body to invoke an exception andthrows
clause is used in method declaration (signature).
throws
子句用于声明异常,throw
关键字用于显式抛出异常。如果我们看到语法明智,则
throw
后跟一个实例变量,throws
后跟异常类名称。关键字
throw
在方法体内使用以调用异常,throws
子句在方法声明(签名)中使用。
For example
例如
throw
扔
throw new Exception("You have some exception")
throw new IOException("Connection failed!!")
throws
投掷
public int myMethod() throws IOException, ArithmeticException, NullPointerException {}
You cannot declare multiple exceptions with
throw
. You can declare multiple exception e.g. public void method()throws IOException,SQLException.checked exceptions can not be propagated with
throw
only because it is explicitly used to throw an particular exception. checked exception can be propagated withthrows
.
您不能使用 声明多个异常
throw
。您可以声明多个异常,例如 public void method()throws IOException,SQLException。不能传播受检查的异常,
throw
因为它显式用于抛出特定的异常。检查的异常可以通过throws
.
Exception propagation:An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b(), which calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception. what is exception propagation?
异常传播:异常从一个方法传播到另一个方法,沿调用堆栈向上传播,直到被捕获。因此,如果 a() 调用 b(),后者调用 c(),后者调用 d(),并且如果 d() 抛出异常,则异常将从 d 传播到 c 到 b 到 a,除非这些方法之一捕获例外。 什么是异常传播?
回答by Subhrajyoti Majumder
throw
use for throwing actual Exception
and throws
declare at method it might throws Exception
.
throw
用于抛出实际Exception
和throws
声明在它可能抛出的方法Exception
。
public int findMax(int[] array) throws Exception{
if(array==null)
throw new NullPointerException(...);
...
}
回答by drew moore
public void someMethod(List<Foo> someList) throws SomeException {
if (someList.isEmpty()) throw new SomeException();
}