Back to all posts

C# Quick Tip: Try/Finally Block

Posted on Jan 04, 2011

Posted in category:
Development
C#

This post is the first of a series of "quick tip" blog postings. These will be shorter articles focused on providing quick tips on various topics. Each posting will be tagged with a single category as well as the "Quick Tips" category to indicate it is a quick tip.

For the first Quick Tip, I want to focus on a language feature of both C# and VB.NET that is not always something people think of. Everyone should be familiar with the Try/Catch/Finally and Try/Catch blocks of code. These are key concepts that are discussed in the introduction to .NETclasses. However, there is another flavor of exception handling that can be used which is a Try/Finally block. In this post, I will show a simple example.

The Code

To jump right in lets look at the following snippet of code.

Try/Finally Example Code
int x = 0;

try
{
   //More logic goes here
   x = int.Parse("Failure");
}
finally
{
   Console.WriteLine(string.Concat("X = ", x.ToString()));
}

Looking at this code the end result should be apparent that "X = 0" will be out to the console, and the exception will bubble up the calling chain.

Why Do I Care?

Now looking at this sample I'm sure there will be many questions that come to mind. The first being WHY might this be helpful? Well more than anything it is a bit of shorthand, if we look at this in a bit longer syntax we could see something like this.

Try/Finally Practical Example
int x = 0;

try
{
   //More logic goes here
   x = int.Parse("Failure");
}
catch(Exception)
{
   throw;
}
finally
{
   Console.WriteLine(string.Concat("X = ", x.ToString()));
}

All this above example does is the same thing, just a bit more longhand. The key here is that it isn't needed. Using the try/finally syntax you can quickly write a block of code that could throw an error and ensure that you always clear up any needed resources using the finally block and never touch the exception.

Overall, just a bit of handy syntax to make code a bit more concise, when you can't handle the exception thrown, but still need to clean up.

Feel free to share comments below.