Main menu:

Site search

Categories

Archive

.NET Finally Blocks

A quick note about try/catch/finally blocks in .NET: the finally block will be executed no matter what! When you’re working with files or connections to servers, please remember to close them whether your code executes properly or fails miserably. It’s good for you, for me and for the world as a whole.

From MSDN:

When an exception occurs, execution stops and control is given to the closest exception handler. This often means that lines of code you expect to always be called are not executed. Some resource cleanup, such as closing a file, must always be executed even if an exception is thrown. To accomplish this, you can use a finally block. A finally block is always executed, regardless of whether an exception is thrown.

Write a comment