12.8.2 在return中使用finally

来源:互联网 发布:香港进出口数据 编辑:程序博客网 时间:2024/05/24 22:44

finally位于try catch之后, 无论是否执行到catch都会执行finally中的语句, 特别要注意的是, 即使try 或 catch中有return, finally语句仍然会在程序返回调用者之前执行

package com.cnsuning.src;public class Main {public Main() {// TODO Auto-generated constructor stub}public static void main(String[] args) {Main m = new Main();m.test(0, 0);m.test(1, 2);}public void test(int a, int b){try{if(a == b && a == 0){throw new Exception("两个数不能都为零");}System.out.println("a:"+a);System.out.println("b:"+b);return;}catch(Exception e){System.out.println(e.getMessage());}finally{System.out.println("finally statement");}}}

两个数不能都为零finally statementa:1b:2finally statement



0 0