Blogs

C# Quick Tip: Try/Finally Block

04 Jan

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 introduction to .NET classes.  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.

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.

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 being 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 cleanup.

Feel free to share comments below.

tags: C#, Quick Tips
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Connect with Mitchel

I hope the information here has been helpful. To stay connected you can also subscribe to blog updates via email, contact Mitchel about consulting services, or reach out for assistance via CodeMendor

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.