Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 10. exception handling: Putting ... > If you have code that ALWAYS should ...

10.11. If you have code that ALWAYS should run, use a finally block

When your program throws an exception, a couple of things can happen. If the exception isn't handled, your program will stop processing and crash. If the exception is handled, your code jumps to the catch block. But what about the rest of the code in your try block? What if you were closing a stream, or cleaning up important resources? That code needs to run, even if an exception occurs, or you're going to make a mess of your program's state. That's where the finally block comes in really handy. It comes after the try and catch blocks. The finally block always runs, whether or not an exception was thrown. Here's how you'd use it to finish the event handling in the Random Excuse button:

private void RandomExcuseButton_Click(object sender, EventArgs e) {
    string[] fileNames = Directory.GetFiles(Folder, "*.excuse");
    if (fileNames.Length == 0) {
        MessageBox.Show("Please specify a folder with excuse files in it",
                        "No excuse files found");
    } else {
        try {
            if (CheckChanged() == true) {
                CurrentExcuse = new Excuse(random, Folder);
            }
        }
        catch (Exception) {
            CurrentExcuse = new Excuse();
            CurrentExcuse.Description = "";
            CurrentExcuse.Results = "";
            CurrentExcuse.LastUsed = DateTime.Now;
            MessageBox.Show(
              "Your excuse file was invalid.",
              "Unable to open a random excuse");
        }
        finally {
            UpdateForm(false);
        }
    }
}


					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial