C#中try catch finally的执行顺序

1.首先明确一点,就是无论怎样,finally必定会执行,即便程序有异常,而且在catch中thorw 了 ,finally仍是会被执行。.net

2.当try和catch中有return时,finally仍然执行。blog

3.finally是在return后面的表达式运算完以后执行的,在执行完return时 ,程序并无跳出,而是进入到finally中继续执行,three

  若是在finally若是对返回值进行了从新赋值,分为两种状况:string

(1)当返回值是值类型(包括string类型,虽然是引用类型,这是特殊的个例)时,返回的值不受影响,io

        就是在trycatch时,返回的值已经肯定了。编译

(2)当返回值是引用类型时,会影响到返回值,eg:class

   public static string[] TestYinYong()
        {
            string[] arr = { "one", "two" };
            try
            {
                throw new Exception();
            }
            catch (Exception)
            {
                return arr;
            }
            finally
            {
                arr[1] = "three";
            }
        }

此时返回的值是:{ "one", "three" };引用

4.finally中不能有return语句,编译都没法经过,提示:控制不能离开finally子句主体程序

 

参考:异常

http://m.blog.csdn.net/kavensu/article/details/8067850

http://blog.csdn.net/jiankunking/article/details/38750023

相关文章
相关标签/搜索