Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend Yet More on Exception Handling

Yet More on Exception Handling

The exception-handling code can be improved further, as illustrated in Listing 4.

Listing 4–More improvements in the exception handling.

string directoryName = "A subdirectory";
string fileName = @"C:\MyNewFile.txt";
Console.WriteLine("This program lists all the files in the directory.");
FileInfo aFile = null;
FileStream fileStream = null;

try
{
    aFile = new FileInfo(fileName);
    fileStream = aFile.Open(FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);

    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"C:\");

    dir.CreateSubdirectory(directoryName);

    foreach (System.IO.FileInfo file in dir.GetFiles("*.*"))
    {
        Console.WriteLine("{0}, {1}", file.Name, file.Length);
    }
    Console.ReadLine();
}
catch (IOException exception)
{
    Console.WriteLine("Got an exception:" + exception.Message);
    Console.ReadLine();
}
finally
{
    if (Directory.Exists(@"C:\" + directoryName))
    {
        Directory.Delete(@"C:\" + directoryName);
    }

    if (fileStream != null)
    {
        fileStream.Close();
    }

    if (aFile != null)
    {
        aFile.Delete();
    }
}

Listing 4 makes two main changes to the code in Listing 3. The first change is moving the following lines:

FileInfo aFile = null;
FileStream fileStream = null;

Notice that these lines are now outside the main try-catch statement. The two objects in these lines are instantiated inside the main try-catch statement, so any disk-related exceptions will still be caught by the code.

The second major change is a finally clause. What's so special about a finally clause? Well, the code inside a finally clause is guaranteed to run, whether or not an exception occurs. This powerful technique gives your code a chance to clean up after it runs. In our example, the cleanup isn't much—a file and a directory get deleted. But imagine a code example that created thousands of file and folders. By using the structured exception-handling mechanism in Listing 4, you get a guaranteed opportunity to clean up any outstanding resource allocations.

If you think about it, the exception handling in Listing 4 is a kind of framework. When you want to add more resources, you simply expand the code. The rules are already set up in Listing 4, so you simply follow those rules and get on with your application coding. That brings us to the next major point in this article:

Rule #3: Effective exception handling helps make your code a good citizen.

In other words, don't rely on the runtime system or the garbage collector to do your dirty work! It's far better programming practice to do your own resource deallocation. Your programming colleagues and your end users will thank you for it.

Next, let's take a look at some issues related to binary file I/O.

  • + Share This
  • 🔖 Save To Your Account