How does the try catch finally block work?

后端 未结 6 1435
耶瑟儿~
耶瑟儿~ 2021-02-06 20:35

In C#, how does a try catch finally block work?

So if there is an exception, I know that it will jump to the catch block and then jump to the finally block.

6条回答
  •  孤城傲影
    2021-02-06 21:28

    The finally block will always execute before the method returns.

    Try running the code below, you'll notice where the Console.WriteLine("executed") of within the finally statement, executes before the Console.WriteLine(RunTry()) has a chance to execute.

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        Console.WriteLine(RunTry());
        Console.ReadLine();
    }
    public static int RunTry()
    {
        try
        {
            throw new Exception();
        }
        catch (Exception)
        {
            return 0;
        }
        finally
        {
            Console.WriteLine("executed");
        }
        Console.WriteLine("will not be executed since the method already returned");
    }
    

    See the result:

提交回复
热议问题