天天看点

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. 控制转移,直接返回,吃掉了异常

        }

    }

}