November 2001
Beginner to intermediate
816 pages
16h 3m
English
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:
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}", ... |
Read now
Unlock full access