网络知识 娱乐 Java|Java中两种抛出异常的方式

Java|Java中两种抛出异常的方式

在Java中有两种抛出异常的方式,一种是throw,直接抛出异常,另一种是throws,间接抛出异常。

直接抛出异常是在方法中用关键字throw引发明确的异常。当throw被执行时,其后语句将不再执行,执行流程将直接寻找catch语句并进行匹配。这种错误不是出错产生,而是人为的抛出。throw抛出异常的格式为

throw ThrowableObject;//例如:throw new ArithmeticException();

Java的异常处理模块中,所有抛出的异常都必须要有对应的“异常处理模块”。也就是说,如果在程序中抛出一个异常,那么在方法中就必须要捕获这个异常。

public class Test { public static void main(String[] args) { System.out.print("now "); try{ System.out.print("is "); throw new NullPointerException(); }catch (NullPointerException e){ System.out.print("the "); } System.out.print("time"); }}now is the time

如果一个方法可能导致一个异常但不处理它,此时要求在方法声明throws子句,通知潜在调用者,在发生异常时沿着调用层次向上传递,由调用它的方法来处理这些异常,这类异常称为申明异常。实例如下

public class Test { private static void p() throws ArithmeticException{ int i; i = 4/0; } public static void main(String[] args) { try { p(); }catch (ArithmeticException e){ System.out.println("除0错误"); } }}

在本实例中,语句I = 4/0;将产生异常,产生异常后方法p()并不进行处理,而是由调用p()的main方法进行处理。

END

主 编 | 张祯悦

责 编 | 刘玉江

where2go 团队


微信号:算法与编程之美

长按识别二维码关注我们!

温馨提示:点击页面右下角“写留言”发表评论,期待您的参与!期待您的转发!