zoukankan      html  css  js  c++  java
  • C#中try catch finally的执行顺序

    1.首先明确一点,就是不管怎样,finally一定会执行,即使程序有异常,并且在catch中thorw 了 ,finally还是会被执行。

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

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

      如果在finally如果对返回值进行了重新赋值,分为两种情况:

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

            就是在trycatch时,返回的值已经确定了。

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

       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

  • 相关阅读:
    Two Sum II
    Subarray Sum
    Intersection of Two Arrays
    Reorder List
    Convert Sorted List to Binary Search Tree
    Remove Duplicates from Sorted List II
    Partition List
    Linked List Cycle II
    Sort List
    struts2结果跳转和参数获取
  • 原文地址:https://www.cnblogs.com/huangshuqiang/p/7850468.html
Copyright © 2011-2022 走看看