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.
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)