流程控制—try_catch_finally中的return/throw

来源:互联网 发布:手机淘宝如何申请贷款 编辑:程序博客网 时间:2024/05/17 21:57

规则一

  1. return和throw等价,都会结束方法;
  2. 程序运行时在catch中遇到return或者throw后,会先运行finally代码块所有的代码,包括return和throw;
  3. 综上return 和 throw new Exception()不能同时运行;

示例一:finally中有return/throw导致catch中return未运行

public class TryCatchFinally {    private String testTry(){        try{            System.out.println("try");        }catch (Exception x){            System.out.println("catch");            throw new RuntimeException("catch");//不会运行        }        finally {            System.out.println("finally");            return "finally";        }    }    public static void main(String[] args) {        System.out.println(new TryCatchFinally().testTry());    }}
原创粉丝点击