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语句。

  • 相关阅读:
    【POJ2176】Folding
    【NOIP2018】赛道修建
    优雅的文本编辑器——Sublime Text 3的搭建与使用
    【NOIP2010】乌龟棋
    【POJ3585】Accumulation Degree
    【POJ3322】Bloxorz I
    python之路_常用模块介绍
    python之路_正则表达式及re模块
    python之路_内置函数及匿名函数
    python之路_递归函数及实例讲解
  • 原文地址:https://www.cnblogs.com/chenwx/p/1425629.html
Copyright © 2011-2022 走看看