Day015 异常处理机制 (2)

以第一个异常为例,我们都知道除数为0肯定是异常,我们就可以自己抛出

public static void main(String[] args) { int a=1; int b=0; try { if(b==0){ throw new ArithmeticException("除数为0");//主动抛出异常 } System.out.println(a/b); } catch (Exception e) { e.printStackTrace(); } finally { } }

输出结果

java.lang.ArithmeticException: 除数为0 at com.dwy.exception.Test2.main(Test2.java:10) throws抛出异常

我们写一个打印两个数相除的结果的方法

public class Test3 { public static void main(String[] args) { int a=1; int b=0; try { new Test3().printDivide(a,b); } catch (ArithmeticException e) { e.printStackTrace(); } } //打印两个数相除的结果 public void printDivide(int a,int b) throws ArithmeticException{ System.out.println(a/b); } }

输出结果

java.lang.ArithmeticException: / by zero at com.dwy.exception.Test3.printDivide(Test3.java:17) at com.dwy.exception.Test3.main(Test3.java:9)

在printDivide函数捕获到异常时,会抛到调用该函数的方法中,在该方法中进行捕获处理。

遇到异常,就意味着你要进步了,这是一件好事。

狂神说java

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwysxy.html