try-finally (C# Reference)
The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.
Example
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.
C# Language Specification
For more information, see the following sections in the C# Language Specification:
5.3.3.14 Try-finally statements
8.11 The try statement
16 Exceptions
See Also
Tasks
How to: Explicitly Throw Exceptions
Concepts
Reference
The try, catch, and throw Statements
Exception Handling Statements (C# Reference)