In this example, there is one invalid conversion statement that causes an exception. When you run the program, you get a run-time error message, but the finally clause will still be executed and display the output.
public class ThrowTest
{
static void Main()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int)o;
}
finally
{
Console.Write("i = {0}", i);
}
}
}
The example above causes System.InvalidCastException to be thrown.
Although an exception was caught, the output statement included in the finally block will still be executed, that is:
i = 123
For more information on finally, see try-catch-finally.
C# also provides the using statement which provides a convenient syntax for the exact same functionality as a try-finally statement.