概念:程序中可能出现的问题
异常体系的顶层父类是Exception
图解
try{可能出现异常的代码} catch (异常类名 变量名) {异常的处理代码}
没有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}}}
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;}
}