If I return out of a try/finally block in C# does the code in the finally always run?

前端 未结 4 554
醉梦人生
醉梦人生 2020-12-05 06:46

It seems like it does as per some initial testing, but what I\'d like to know is if it is guaranteed to return or if in some cases it can not return? This i

4条回答
  •  Happy的楠姐
    2020-12-05 07:29

    Here are some examples:

    Environment.FailFast()

            try
            {
                Console.WriteLine("Try");
                Environment.FailFast("Test Fail");
    
            }
            catch (Exception)
            {
                Console.WriteLine("catch");
            }
            finally
            {
                Console.WriteLine("finally");
            }
    

    The output is only "Try"

    Stackoverflow

            try
            {
                Console.WriteLine("Try");
                Rec();
            }
            catch (Exception)
            {
                Console.WriteLine("catch");
            }
            finally
            {
                Console.WriteLine("finally");
            }
    

    Where Rec is:

        private static void Rec()
        {
            Rec();
        }
    

    The output is only "Try" and the process terminates due to StackOverflow.

    Unhanded exception

            try
            {
                Console.WriteLine("Try");
                throw new Exception();
            }
            finally
            {
                Console.WriteLine("finally");
            }
    

提交回复
热议问题