finally的作用

finally语法:

try{
可能包含异常的代码

}catch(异常类 变量名){
异常处理代码

}…(多个catch)

finally{
后置处理代码

}

demo1

public static void main(String[] args) {
 
    try {
 
        test();
 
    } catch (Exception e) {
 
        e.printStackTrace();
 
    }
 
}
 
 
 
public static void test() throws Exception {
 
    try {
 
        throw new Exception("lalalala");
 
    }catch (RuntimeException e){
 
        e.printStackTrace();
 
    }finally {
 
        System.out.println("finally");
 
    }
 
}
 

输出:

finally

java.lang.Exception: lalalala

at helloworld.exception.FinallyTeach.test(FinallyTeach.java:15)

at helloworld.exception.FinallyTeach.main(FinallyTeach.java:7)

结论:

异常如果没有被捕获,会执行finally的代码

demo2

public static void main(String[] args) {
 
    try {
 
        test2();
 
    } catch (Exception e) {
 
        e.printStackTrace();
 
    }
 
}
 
 
 
public static void test2() throws Exception {
 
    try {
 
        throw new RuntimeException("abcd");
 
    }catch (RuntimeException e){
 
        e.printStackTrace();
 
    }finally {
 
        System.out.println("finally");
 
    }
 
}
 

输出:

finally

java.lang.RuntimeException: abcd

at helloworld.exception.FinallyTeach.test2(FinallyTeach.java:25)

at helloworld.exception.FinallyTeach.main(FinallyTeach.java:7)

结论: 如果异常被捕获,依然会执行finally里的代码

1.无论异常是否被捕获,finally的代码一定会被执行。
2.finally里适合存放释放资源、后续处理的代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值