异常注意事项_多异常的捕获处理和异常注意事项_finally有return语句
异常注意事项_多异常的捕获处理
多个异常使用捕获又该如何处理呢? 1. 多个异常分别处理
2. 多个异常一次捕获,多次处理
3. 多个异常一次捕获一次处理
public class Demo01Exception { public static void main(String[] args) { //1. 多个异常分别处理。 /* try { int[] arr = {1,2,3}; System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3 }catch (ArrayIndexOutOfBoundsException e){ System.out.println(e); } try{ List<Integer> list = List.of(1, 2, 3); System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3 }catch (IndexOutOfBoundsException e){ System.out.println(e); }*/ //2. 多个异常一次捕获,多次处理。 /*try { int[] arr = {1,2,3}; //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3 List<Integer> list = List.of(1, 2, 3); System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3 }catch (ArrayIndexOutOfBoundsException e){ System.out.println(e); }catch (IndexOutOfBoundsException e){ System.out.println(e); }*/ /* 一个try多个catch注意事项: catch里边定义的异常变量,如果有子父类关系,那么子类的异常变量必须写在上边,否则就会报错 ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException */ /*try { int[] arr = {1,2,3}; //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3 List<Integer> list = List.of(1, 2, 3); System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3 }catch (IndexOutOfBoundsException e){ System.out.println(e); }catch (ArrayIndexOutOfBoundsException e){ System.out.println(e); }*/ //3. 多个异常一次捕获一次处理。 /*try { int[] arr = {1,2,3}; //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3 List<Integer> list = List.of(1, 2, 3); System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3 }catch (Exception e){ System.out.println(e); }*/ //运行时异常被抛出可以不处理。即不捕获也不声明抛出。 //默认给虚拟机处理,终止程序,什么时候不抛出运行时异常了,在来继续执行程序 int[] arr = {1,2,3}; System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3 List<Integer> list = Arrays.asList(1,2,3); System.out.println(list); System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3 System.out.println("后续代码!"); } }
如果finally有return语句,永远返回finally中的结果,避免该情况.
public class Demo02Exception { public static void main(String[] args) { int a = getA(); System.out.println(a); } //定义一个方法,返回变量a的值 public static int getA(){ int a = 10; try{ return a; }catch (Exception e){ System.out.println(e); }finally { //一定会执行的代码 a = 100; return a; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)