当前位置: 首页 > 图灵资讯 > 技术篇> JAVA——38.finally块

JAVA——38.finally块

来源:图灵教育
时间:2023-05-25 09:18:16

练习1。由于异常已被捕获和处理,他仍将执行异常后的代码

package pkg5;public class Test1 {    String x;    public static void main(String[] args) {                Test1 test1=new Test1();        //1        try{                            System.out.println(5/0);    //2        }catch(ArrayIndexOutOfBoundsException e) {//3            test1.x="hello world";                             System.out.println(test1.x.length());        }catch(NullPointerException e) { //4            test1.x="hello world";                             System.out.println(test1.x.length());        }catch(Exception e) { //5            test1.x="hello world";                             e.printStackTrace();//6        }        System.out.println("end");        //}    }}

JAVA——38.finally块_System

练习2,finally块:无论如何执行try、catch块,都会执行finally块(如无异常,直接执行try块,如有异常,执行catch块)

package pkg5;public class Test1 {    String x;    public static void main(String[] args) {                Test1 test1=new Test1();        //1        try{                            System.out.println(5/1);    //2        }catch(ArrayIndexOutOfBoundsException e) {//3            test1.x="hello world";                             System.out.println(test1.x.length());        }catch(NullPointerException e) { //4            test1.x="hello world";                             System.out.println(test1.x.length());        }catch(Exception e) { //5                       e.printStackTrace();//6        }finally {            System.out.println("finally");        }        System.out.println("end");//因为异常已经被捕获和处理,因此,他在执行异常代码后仍会执行代码    }}

JAVA——38.finally块_System_02