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