天天看點

finally塊中不允許使用return,continue或break的原因

finally塊中不允許使用return,continue或break的原因

一個try塊可以不執行finally子句就能夠退出的唯一方法是通過調用System.exit()方法來實作的。

如果控制因為一個return,continue或break語句離開這個try塊,那麼finally快會在控制轉移到它的新的目标代碼之前執行.

也就是說如果在finally塊中使用return,continue或break,則會把抛出的異常吃掉。

package test;

public class TryTest {

    public static void main(String[] args) {

        try {

            System.out.println(TryTest.test());// 傳回結果為true其沒有任何異常

        } catch (Exception e) {

            System.out.println("Exception from main");

            e.printStackTrace();

        }

    }

    public static boolean test() throws Exception {

        try {

            throw new Exception("Something error");// 1.抛出異常

        } catch (Exception e) {// 2.捕獲的異常比對(聲明類或其父類),進入控制塊

            System.out.println("Exception from e");// 3.列印

            return false;// 4. return前控制轉移到finally塊,執行完後再傳回

        } finally {

            return true; // 5. 控制轉移,直接傳回,吃掉了異常

        }

    }

}