C# Exceptions - The finally Block
(Page 2 of 4 )
A finally block always executes—whether or not an exception is thrown and whether or not the try block runs to completion. finallyblocks are typically used for cleanup code.
Afinally block executes either:
- After acatchblock finishes
- After control leaves thetryblock because of ajumpstatement (e.g.,returnorgoto)
- After thetryblock ends
Afinallyblock helps add determinism to a program. In the following example, the file that we open always gets closed, regardless of whether:
- Thetryblock finishes normally.
- Execution returns early because the file is empty (EndOfStream).
AnIOExceptionis thrown while reading the file.
using System;
using System.IO;
class Test
{
static void Main ()
{
StreamReader reader = null;
try
{
reader = File.OpenText ("file.txt");
if (reader.EndOfStream) return;
Console.WriteLine (reader.ReadToEnd ( ));
}
finally
{
if (reader != null) reader.Dispose ();
}
}
}
In this example, we closed the file by callingDisposeon theStreamReader. CallingDisposeon an object, within afinallyblock, is a standard convention throughout the .NET Framework and is supported explicitly in C# through theusingstatement.
The using statement
Many classes encapsulate unmanaged resources, such as file handles, graphics handles, or database connections. These classes implement System.IDisposable, which defines a single parameterless method named Dispose to clean up these resources. The usingstatement provides an elegant syntax for instantiating anIDisposableobject and then calling itsDisposemethod within afinallyblock.
The following:
using (StreamReader reader = File.OpenText ("file.txt"))
{
...
}
is precisely equivalent to:
StreamReader reader = File.OpenText ("file.txt");
try
{
...
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
We cover the disposal pattern in more detail in Chapter 12 .
Next: Throwing Exceptions >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|