Section A.1. Why Exception Handling?

Table of contents:

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

graphics/appfig01.gif

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

graphics/appfig02.gif

GDI+: The Next-Generation Graphics Interface

Your First GDI+ Application

The Graphics Class

Working with Brushes and Pens

Colors, Fonts, and Text

Rectangles and Regions

Working with Images

Advanced Imaging

Advanced 2D Graphics

Transformation

Printing

Developing GDI+ Web Applications

GDI+ Best Practices and Performance Techniques

GDI Interoperability

Miscellaneous GDI+ Examples

Appendix A. Exception Handling in .NET



GDI+ Programming with C#
GDI+ Programming with C#
ISBN: 073561265X
EAN: N/A
Year: 2003
Pages: 145

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net