Java中抛出和抛出的区别? [英] Difference between throw and throws in Java?

查看:169
本文介绍了Java中抛出和抛出的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都能用一个例子清楚地说明Java异常处理中throw和throws之间的区别吗?我试过谷歌搜索但无法得出结论。请帮助

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

推荐答案


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

  1. throws clause is used to declare an exception and throw keyword is used to throw an exception explicitly.

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

If we see syntax wise then throw is followed by an instance variable and throws is followed by exception class names.

在方法体内使用关键字 throw 来调用异常,抛出子句用于方法声明(签名)。

The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).

例如

抛出

throw new Exception("You have some exception")
throw new IOException("Connection failed!!")

抛出

public int myMethod() throws IOException, ArithmeticException, NullPointerException {}




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

  1. You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws IOException,SQLException.

检查的异常不能仅使用 throw 传播因为它明确用于抛出特定异常。已检查的异常可以使用 throws传播

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

异常传播:异常传播从方法到方法,向上传递调用堆栈,直到它被捕获。因此,如果a()调用b(),调用c(),调用d(),并且d()抛出异常,异常将从d传播到c到b传播到a,除非这些方法中的一个捕获例外。
什么是异常传播?

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?

这篇关于Java中抛出和抛出的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆