首页 > 编程知识 正文

finally关键字,finally和final有什么区别

时间:2023-05-05 03:44:08 阅读:114692 作者:1182

finally语法:

try{

可能包含异常的代码

}catch (异常系统变量名称) {

异常处理代码

() (多个catch ) ) )。

法瑞{

后处理代码

}

demo1

publicstaticvoidmain (字符串[ ] args ) try ) test ); }catch(exceptione ) { e.printStackTrace ); } }公共静态语音测试() throws exception (try ) thrownewexception('Lalalala ' ); }运行时任务(运行时任务) { e.printStackTrace ); (finally ) system.out.println ) (finally ); }输出:

金融

Java.lang.exception : Lala Lala

at hello world.exception.finally teach.test (finally teach.Java :15 ) ) ) )。

at hello world.exception.finally teach.main (finally teach.Java :7 ) ) )。

结论:

如果未捕获到异常,则会执行finally代码

demo2

publicstaticvoidmain (字符串[ ] args ) try ) test2); }catch(exceptione ) { e.printStackTrace ); } publicstaticvoidtest2(throws exception ) try (thrownewruntimeexception ) ' ABCD '; }运行时任务(运行时任务) { e.printStackTrace ); (finally ) system.out.println ) (finally ); }输出:

金融

Java.lang.runtime exception : ABCD

at hello world.exception.finally teach.test2(finally teach.Java :25 ) ) ) ) ) ) ) ) )。

at hello world.exception.finally teach.main (finally teach.Java :7 ) ) )。

结论捕获:异常时,仍然执行finally的代码

1 .无论是否捕获到异常,finally的代码都必须执行。

2 .适合于将资源释放到2.finally并存储后续处理的代码

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。