zoukankan      html  css  js  c++  java
  • try catch finally与return的执行顺序

    测试1:
        public static int test1()
        {
            int i = 1;
            try
            {
                return ++i;
            }
            finally
            {
                ++i;
                Console.WriteLine("finally:" + i);
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Main:" + test1());
        }
    结果:
    finally:3
    Main:2


    测试2:
        public static int test2()
        {
            int i = 1;
            try
            {
                throw new Exception();
            }
            catch
            {
                return ++i;
            }
            finally
            {
                ++i;
                Console.WriteLine("finally:" + i);
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Main:" + test2());
        }
    结果:
    finally:3
    Main:2


    测试3:
        public static int test3()
        {
            try{}
            finally
            {
                return 1;
            }
        }

    结果:
    编译错误,控制不能离开 finally 子句主体。


    结论:

    1.不管出没出现异常,finally块中的语句都会执行;
    2.当try或catch块中有return语句时,finally块中的语句仍会执行;
    3.finally块中的语句是在函数返回前执行的,但函数返回值是在finally块中语句执行前确定的;
    4.finally块中不能包含return语句。

  • 相关阅读:
    json server服务器
    Vue中父子组件通讯——组件todolist
    Vue基础语法
    mac双系统下ubuntu卡在开机密码登录界面卡死
    GBK转UTF8
    Geek/Git中文怎么读
    Javascript正则表达入参是null
    【MySQL】解决You can't specify target table 'user_cut_record_0413' for update in FROM clause
    aglio报错解决
    Sublime美化配置
  • 原文地址:https://www.cnblogs.com/zhc088/p/1701544.html
Copyright © 2011-2022 走看看