C# Simplified, part 5: Error Handling and Files - Finally clause
(Page 3 of 8 )
You have already seen from the above explanations that the statements inside the catch block will be executed only if an error occurs. However, there may be situations where something should be performed whether an exception has occurred or not. In such cases, you can make use of the finally clause, as shown in listing 5.4:
Listing 5.4
using System;
class FinallyDemo
{
public static void Main()
{
try
{
int x = 15;
int y = 0;
int z = x/y;
Console.WriteLine(z);
}
catch(DivideByZeroException e)
{
Console.WriteLine("Error occurred " +e);
}
finally
{
Console.WriteLine("Thank you for using the program");
}
}
}
In the above code, the statement inside the finally block will always execute. The final output looks like this:
Error occurred System.DivideByZeroException: Attempted to divide by zero.
at FinallyDemo.Main()
Thank you for using the program
Next: Accessing files and directories >>
More C# Articles
More By Anand Narayanaswamy