How does the try catch finally block work?

后端 未结 6 1436
耶瑟儿~
耶瑟儿~ 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:22

    Yes, Finally will always execute.

    Even if there is no catch block after try, finally block will still execute.

    Basically finally can be used to release resources such as a file streams, database connections and graphics handlers without waiting for the garbage collector in the runtime to finalize the object.

           try
            {
                int a = 10;
                int b = 0;
                int x = a / b;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("Finally block is executed");
            }
            Console.WriteLine("Some more code here");
    

    Output:

    System.DivideByZeroException: Attempted to divide by zero.

    Finally block is executed

    Rest of the code

    Source : Exception handling in C# (With try-catch-finally block details)

提交回复
热议问题