Java对异常处理或抛出之后,后面代码会不会再执行?
生活随笔
收集整理的这篇文章主要介绍了
Java对异常处理或抛出之后,后面代码会不会再执行?
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
一、测试代码:
public class TestException {public static void main(String[] args) throws Exception {int[] i = {1, 2, 3};try {System.out.println(i[3]);} catch (Exception e) {e.printStackTrace();}System.out.println("异常后1");//可以执行try {System.out.println(i[3]);} catch (Exception e) {throw new Exception("错误" + e);}System.out.println("异常后2");//不能执行} }结果:
java.lang.ArrayIndexOutOfBoundsException: 3at TestException.main(TestException.java:15) Exception in thread "main" java.lang.Exception: 错误java.lang.ArrayIndexOutOfBoundsException: 3at TestException.main(TestException.java:24) 异常后1二、 集合测试:
public class Test {public static void main(String[] args) throws Exception {List<Student> list = new ArrayList<>();Student student1 = new Student("张三", 18);Student student2 = new Student("李四", 18);Student student3 = new Student("王五", 18);list.add(student1);list.add(student2);list.add(student3);for (Student student : list) {if (student.getName().equals("李四")) {throw new Exception("李四");}System.out.println(student);//王五没有输出}} }结果:
Student{name='张三', age=18} Exception in thread "main" java.lang.Exception: 李四at Test.main(Test.java:15)三、 结论:
总结
以上是生活随笔为你收集整理的Java对异常处理或抛出之后,后面代码会不会再执行?的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 全局错误码
- 下一篇: Java 防抖动函数的实现