I'm teaching myself C# and I am up to studying the try, catch and finally. The book I'm using is discussing how the finally block runs regardless of whether or not the try block is successful. But, wouldn't code that is written outside of the catch block be run anyway even if it wasn't in finally? If so, what's the point of finally? This is the example program the book is providing:
class myAppClass
{
public static void Main()
{
int[] myArray = new int[5];
try
{
for (int ctr = 0; ctr <10; ctr++)
{
myArray[ctr] = ctr;
}
}
catch
{
Console.WriteLine("Exception caught");
}
finally
{
Console.WriteLine("Done with exception handling");
}
Console.WriteLine("End of Program");
Console.ReadLine();
}
}
These are scenarios where a finally
is useful:
try
{
//Do something
}
catch (Exception e)
{
//Try to recover from exception
//But if you can't
throw e;
}
finally
{
//clean up
}
Usually you try to recover from exception or handle some types of exceptions, but if you cannot recover of you do not catch a specific type of exception the exception is thrown to the caller, BUT the finally
block is executed anyway.
Another situation would be:
try
{
//Do something
return result;
}
finally
{
//clean up
}
If your code runs ok and no exceptions is thrown you can return from the try
block and release any resources in the finally
block.
In both cases if you put your code outside the try
, it will never be executed.
Here is a simple example to show code that is written outside of the catch block does not run anyway even if it wasn't in finally!
try
{
try { throw new Exception(); }
finally { Console.WriteLine("finally"); }
Console.WriteLine("Where am I?");
}
catch { Console.WriteLine("catched"); }
and the output is
finally
catched
Please read the MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With