How does the try catch finally block work?
Yes the finally clause gets exeucuted if there is no exception. Taking an example
try
{
int a = 10;
int b = 20;
int z = a + b;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Executed");
}
So here if suppose an exception occurs also the finally gets executed.
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:
Hello World!
executed
0
Yes, the finally block gets run whether there is an exception or not.
Try [ tryStatements ] [ Exit Try ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] [ Exit Try ] ] [ Catch ... ] [ Finally [ finallyStatements ] ] --RUN ALWAYS End Try
See: http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx