Section A.1. Why Exception Handling?

A 1 Why Exception Handling?

If you've been writing software for very long, you probably already know why you want to handle exceptions. Have you ever seen a program crash and display a weird message that doesn't make any sense? This is what happens when developers do not handle exceptions properly. Let's look at a simple example. Listing A.1 opens a file named c:abc.txt.

Listing A.1 Opening a file

using System; using System.IO; namespace ListingA1andA2 { class Class1 { static void Main(string[] args) { File.Open("c:\abc.txt", FileMode.Open); } } }

What if the file does not exist? We get the error message shown in Figure A.1. We are fortunate that CLR handles so much for us because otherwise this error message could have been a lot worse.

Figure A.1. An error generated from Listing A.1

Now let's make a small modification to our program. The new code is shown in Listing A.2. This time we use a simple try...catch block to handle the exception.

Listing A.2 A simple exception handling block

using System; using System.IO; namespace ListingA1andA2 { class Class1 { static void Main(string[] args) { try { File.Open("c:\abc.txt", FileMode.Open); } catch (Exception exp) { Console.WriteLine(exp.Message); } } } }

Figure A.2 shows the output from the modified program. Not only is the exception handled, but also the cause of the exception is reported.

Figure A.2. An exception-handled error message

Категории