Java基础-异常
迪丽瓦拉
2025-05-28 12:45:34
0

1.异常概述

概念:程序中可能出现的问题

异常体系的顶层父类是Exception

                                                                                      图解 

 

 2.异常的处理方式

   2.1 JVM默认的处理方式

  1. 把异常的名称和原因以及出现异常的位置大的信息输出在控制台
  2. 程序停止执行,下面的代码不会再执行了

   2.2 自己处理(捕获异常)

     try{可能出现异常的代码} catch (异常类名  变量名) {异常的处理代码}

   2.2.1 try catch finally 执行顺序

             没有return 语句

                1.try没有异常:顺序为try→finally

                2.try有异常:顺序为try→catch→finally

             有return 语句

                 1.try里有return

当try中带有return时,会先执行return前的代码,然后暂时保存需要return的信息,再执行finally中的代码,最后再通过return返回之前保存的信息。

package cn.sxau.异常;public class 捕获异常的执行顺序 {public static void main(String[] args) {System.out.println(testReturn1());}private static int testReturn1() {int i = 1;     //第1步,1try {i++;   //第2步, 2 System.out.println("try:" + i);  //第3步,输出 try:2return i;   //第3步,得到2  第7步 输出  2} catch (Exception e) {i++;    System.out.println("catch:" + i);} finally {i++;   //第5步,3 System.out.println("finally:" + i);  //第6步,输出 finally :3}return i;}}

                 2.catch里有return

catch中return与try中一样,会先执行return前的代码,然后暂时保存需要return的信息,再执行finally中的代码,最后再通过return返回之前保存的信息

package cn.sxau.异常;public class 捕获异常的执行顺序 {public static void main(String[] args) {System.out.println(testReturn1());}private static int testReturn1() {int i = 1;   // 第一步try {i++;  //第二步  得到 i=2System.out.println("try:" + i);  //第三步  输出 try:2int x = i / 0 ; //异常} catch (Exception e) {i++;  //第4步: i= 3System.out.println("catch:" + i);  //第5步: 输出 catch:3return i;  //第6步:  得到 3   第9步 ,输出3} finally {i++; //第7步: i= 4System.out.println("finally:" + i); //第8步 ,输出 finally = 4}return i;}}

                 3.finally里有return

当finally中有return的时候,try中的return会失效,JVM是忽略了try中的return语句。在执行完finally的return之后,就不会再执行try中的return

package cn.sxau.异常;public class 捕获异常的执行顺序 {public static void main(String[] args) {System.out.println(testReturn4());}private static int testReturn4() {int i = 1;   //第一步 1try {i++;  //第二步   i=2System.out.println("try:" + i);  //第三步   输出try: 2return i;  //第4步 :得到 2} catch (Exception e) {i++;System.out.println("catch:" + i);return i;} finally {i++;  //第5步 , i=3System.out.println("finally:" + i); //第6步 : 输出 finally:3return i; //第7步:输出 3}}}

   2.3 抛出异常

  1. throws:写在方法定义处,表示声明一个异常告诉调用者,使用本方法可能会有那些异常
  2. throw:写在方法里面,结束方法,手动抛出异常对象,交给调用者方法下面得代码不再执行
package cn.sxau.异常;public class 抛出异常 {public static void main(String[] args) throws Exception {int[] arr = {1, 2, 3, 4, 5};System.out.println(getMax(arr));}public static int getMax(int[] arr) {if(arr == null){throw new NullPointerException();}if(arr.length ==0){throw new ArrayIndexOutOfBoundsException();}System.out.println("测试代码");int max = 0;for (int s : arr) {if (max < s) {max = s;}}return max;}
}

 

相关内容