The finally Statement

In some instances, throwing an exception and unwinding the stack can create a problem. For example, if you opened a file, connected to a database, or otherwise committed a resource, you might need an opportunity to close the file or database connection. As you saw in the previous examples, when an exception is thrown, it can leave behind code in the method that never gets executed. If that orphaned code is where you closed the file, your program could end without cleaning up after itself.

If there is some action you must take regardless of whether an exception is thrown, such as closing a file, you have two strategies to choose from. One approach is to enclose the dangerous action in a try block and then to perform the necessary action (close the file) in both the catch and try blocks. However, this is an ugly duplication of code, and it’s error-prone. C# provides a better alternative in the finally block.

You create a finally block with the keyword finally, and you enclose the block in braces. The code in the finally block is guaranteed to be executed regardless of whether an exception is thrown. The TestFunc() method in Example 16-5 simulates opening a file as its first action. The method then undertakes some mathematical operations, and then the file is closed.

Tip

A finally block can be created with or without catch blocks, but a finally block requires a try block to execute. It is an error to exit a finally block with break, continue, return, or goto.

It is ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.