The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits. The try-finally statement takes the form:
try try-block finally finally-block
where:
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.
In this example, there is one illegal 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.
// try-finally using System; public class TestTryFinally { public static void Main() { int i = 123; string s = "Some string"; object o = s; try { i = (int) o; // Illegal conversion: // o contains a string not an int } finally { Console.Write("i = {0}", i); } } }
i = 123
Caught exception: System.InvalidCastException
at TestTryFinally.Main()
Although an exception was caught, the output statement included in the finally block was executed.
For more information on finally, see try-catch-finally.
C# Keywords | Compare to C++ | Exception Handling Statements | throw | try-catch | Grammar