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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:47:50  来源:igfitidea点击:

Difference between throw and throws in Java?

javathrowthrows

提问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

  1. throwsclause is used to declare an exception and throwkeyword is used to throw an exception explicitly.

  2. If we see syntax wise then throwis followed by an instance variable and throwsis followed by exception class names.

  3. The keyword throwis used inside method body to invoke an exception and throwsclause is used in method declaration (signature).

  1. throws子句用于声明异常,throw关键字用于显式抛出异常。

  2. 如果我们看到语法明智,则throw后跟一个实例变量,throws后跟异常类名称。

  3. 关键字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 {}
  1. You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws IOException,SQLException.

  2. checked exceptions can not be propagated with throwonly because it is explicitly used to throw an particular exception. checked exception can be propagated with throws.

  1. 您不能使用 声明多个异常throw。您可以声明多个异常,例如 public void method()throws IOException,SQLException。

  2. 不能传播受检查的异常,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

throwuse for throwing actual Exceptionand throwsdeclare at method it might throws Exception.

throw用于抛出实际Exceptionthrows声明在它可能抛出的方法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();
}