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并存储后续处理的代码