finally Blocks

Many times a program ends when an exception occurs. This is okay if that's part of the design, but sometimes there are system resources that need to be released. This is the purpose of the finally block. It performs any necessary cleanup chores prior to program exit. The finally block is guaranteed to be executed before a method exits. Listing 10.2 shows an example of how to use it:

Listing 10.2. The finally Block: Exceptions2.cs
 using System; using System.IO; public class Exceptions { public static int Main(string[] args) { byte[] myStream = new byte[3]; StreamWriter sw = new StreamWriter("exceptions.txt"); try { for (byte b=0; b < 10; b++) { sw.WriteLine("Byte {0}: {1}", b+1, b); myStream[b] = b; } } catch (Exception e) { Console.WriteLine("{0}", ...

Get C# Unleashed 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.