1. 程式人生 > >java中異常處理finally和return語句的執行順序

java中異常處理finally和return語句的執行順序

  1. finally程式碼塊的語句在return之前一定會得到執行
  2. 如果try塊中有return語句,finally程式碼塊沒有return語句,那麼try塊中的return語句在返回之前會先將要返回的值儲存,之後執行finally程式碼塊,最後將儲存的返回值返回,finally程式碼塊雖然對返回值進行修改也不影響返回值,因為要返回的值在執行finally程式碼塊之前已經儲存了,最終返回的是儲存的舊值。
  3. 如果try塊和finally塊都有返回語句,那麼雖然try塊中返回值在執行finally程式碼塊之前被儲存了,但是最終執行的是finally程式碼塊的return語句,try塊中的return語句不再執行。
  4. catch塊和try塊類似,會在執行finally程式碼塊執行前儲存返回值的結果,finally語句中有return語句則執行finally的return語句,沒有則執行catch塊中的return語句,返回之前的儲存值。

測試程式碼如下:

public class Main {
    public static void main(String[] args) {
        System.out.println(test1(0));
        System.out.println(test2(0));
        System.out.println(test3(0));
        System.out
.println(test4(0)); } public static int test1(int b){ try { b+=10; return b; } catch (Exception e) { e.printStackTrace(); b=-1; return b; } finally { b+=100; return b; } } public
static int test2(int b){ try { b+=10; return b; } catch (Exception e) { e.printStackTrace(); b=-1; return b; } finally { b+=100; } } public static int test3(int b){ try { b/=0; return b; } catch (Exception e) { e.printStackTrace(); b=-1; return b; } finally { b+=100; return b; } } public static int test4(int b){ try { b/=0; return b; } catch (Exception e) { e.printStackTrace(); b=-1; return b; } finally { b+=100; } } }

程式執行結果

test1方法執行finally的return語句,返回110
test2方法執行try的return語句,返回10,雖然finally中對返回值b進行了修改,但是無濟於事,返回的是try中儲存的舊值。
test3方法執行finally中的return語句,返回99。
test4方法執行catch的return語句,返回-1。