投
Java中的throw关键字用于显式地从方法或任何代码块抛出异常。我们两个都可以 选中或未选中的异常 .throw关键字主要用于抛出自定义异常。
语法:
throw InstanceExample:throw new ArithmeticException("/ by zero");
但这个例外就是, 例子 一定是那种 可抛出 或者是 可抛出 例如Exception是Throwable和Exception的子类 用户定义的异常通常扩展异常类 与C++不同,数据类型如int、char、浮动或不可丢弃类不能用作异常。
在执行throw语句和最近的封闭语句后,程序的执行流立即停止 尝试 块被检查,看它是否有 接住 与异常类型匹配的语句。如果找到匹配项,则CONTROLED将被转移到该语句,否则将被包含在下一个语句中 尝试 块被检查等等。如果没有匹配 接住 则默认异常处理程序将停止程序。
JAVA
// Java program that demonstrates the use of throw class ThrowExcep { static void fun() { try { throw new NullPointerException( "demo" ); } catch (NullPointerException e) { System.out.println( "Caught inside fun()." ); throw e; // rethrowing the exception } } public static void main(String args[]) { try { fun(); } catch (NullPointerException e) { System.out.println( "Caught in main." ); } } } |
输出:
Caught inside fun().Caught in main.
另一个例子:
JAVA
// Java program that demonstrates the use of throw class Test { public static void main(String[] args) { System.out.println( 1 / 0 ); } } |
输出:
Exception in thread "main" java.lang.ArithmeticException: / by zero
投掷
throws是Java中的一个关键字,用于方法的签名中,以指示此方法可能会抛出列出的类型异常之一。这些方法的调用方必须使用try-catch块来处理异常。
语法:
type method_name(parameters) throws exception_listexception_list is a comma separated list of all the exceptions which a method might throw.
在一个程序中,如果有可能引发一个异常,那么编译器总是警告我们,并强制我们处理这个检查过的异常,否则我们将得到编译时错误 必须捕获或声明要抛出未报告的异常XXX .为了防止这种编译时错误,我们可以通过两种方式处理异常:
- 通过使用 试着接住
- 通过使用 投掷 关键词
我们可以使用throws关键字将异常处理的责任委托给调用方(它可能是一个方法或JVM),然后调用方方法负责处理该异常。
JAVA
// Java program to illustrate error in case // of unhandled exception class tst { public static void main(String[] args) { Thread.sleep( 10000 ); System.out.println( "Hello Geeks" ); } } |
输出:
error: unreported exception InterruptedException; must be caught or declared to be thrown
说明: 在上面的程序中,我们得到了编译时错误,因为如果主线程进入睡眠状态,则有可能出现异常,其他线程则有机会执行main()方法,这将导致InterruptedException。
JAVA
// Java program to illustrate throws class tst { public static void main(String[] args) throws InterruptedException { Thread.sleep( 10000 ); System.out.println( "Hello Geeks" ); } } |
输出:
Hello Geeks
说明: 在上面的程序中,通过使用throws关键字,我们处理了InterruptedException,我们将得到如下输出: 你好,极客们
另一个例子:
JAVA
// Java program to demonstrate working of throws class ThrowsExecp { static void fun() throws IllegalAccessException { System.out.println( "Inside fun(). " ); throw new IllegalAccessException( "demo" ); } public static void main(String args[]) { try { fun(); } catch (IllegalAccessException e) { System.out.println( "caught in main." ); } } } |
输出:
Inside fun().caught in main.
关于关键字,需要记住的要点:
- 只有选中的异常才需要throws关键字,而对未选中的异常使用throws关键字则毫无意义。
- throws关键字仅用于说服编译器,使用throws关键字并不能防止程序异常终止。
- 通过throws关键字的帮助,我们可以向方法的调用方提供有关异常的信息。
参考: Java–Herbert Schildt的完整参考资料
本文由 普拉蒂克·阿加瓦尔 还有Bishal Dubey .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。