When an exception occurs, execution terminates and the control is handed over to the nearest exception-handling statement, which means that it cannot be performed according to the normal design idea. While some resource cleanup, such as closing a file, must always be performed, even if there is an exception, the finally block can be used to implement the feature. Finally blocks are used to clear any resources allocated in a try block and to run the code that must be executed, even in the event of an exception. Control is always passed to the finally block, regardless of how the try block exits.
Use of the example try-catch-finally statement
In this example, there is an invalid conversion statement that causes an exception, and when the program is run, the user receives a run-time error message, but the finally clause continues to execute and the output is displayed. The program code is as follows.
Using System;
public class MainClass
{
static void Main ()
{
int i = 123;
string s = "Some string";
http://www.bianceng.cn
Object o = S;
Try
{
i = (int) o;
}
catch { }
Finally
{
Console.Write ("i = {0}", i);
}
Console.read ();
}
}