Section A.2. Understanding the try...catch Block

A 2 Understanding the try catch Block

If you come from a Visual Basic background, we recommend that you just forget about unstructured exception handling and learn this new approach using the try...catch statement. After you finish reading this appendix, you'll find the structured approach much better!

A.2.1 The try...catch Statement

Using the try...catch statement is very straightforward. First we decide which code we want the error handler to monitor by placing that code inside the try block. When an exception occurs in the encapsulated code, a control goes to the catch block that handles the exception. A simple template for a try...catch block is shown in Listing A.3.

Listing A.3 A simple try...catch block

try
{
 // Place the code that may generate
 // an exception in this block
}
catch ( exception type)
{
 // This code executes when the try block fails and
 // the filter on the catch statement is true.
 // Here you can write your own custom error message
 // or get the message description or other details
 // from the exception class.
}

A.2.2 The try...catch...finally Statement

The try...catch...finally statement is an extended version of the try...catch statement. If an error occurs during execution of any of the code inside the try section, the control moves to the catch block when the filter condition is true. The finally block always executes last, just before the error handling block loses scope, regardless of whether an exception has occurred. The finally block is the perfect place to close files and dispose of objects. A simple try...catch...finally statement is shown in Listing A.4.

Listing A.4 A simple try...catch...finally statement

try
{
 // Place the code that may generate
 // an exception in this block
}
catch ( exception type)
{
 // This code executes when the try block fails and
 // the filter on the catch statement is true.
 // Here you can write your own custom error message
 // or get the message description or other details
 // from the exception class.
}
finally
{
 // Release and dispose of objects and
 // other resources here
}

Listing A.5 allocates resources at the beginning of the method and releases them inside the finally block. Regardless of whether an exception occurs, execution control will pass to the finally block and release the resources.

Listing A.5 Disposing of objects inside the finally block

private void TestExpBtn_Click(object sender,
 System.EventArgs e)
{
 // Create a Graphics object
 Graphics g = this.CreateGraphics();
 g.Clear(this.BackColor);
 // Create pens and brushes
 Pen redPen = new Pen(Color.Red, 1);
 Pen bluePen = new Pen(Color.Blue, 2);
 Pen greenPen = new Pen(Color.Green, 3);
 SolidBrush greenBrush =
 new SolidBrush(Color.Green);
 // Put whatever code you think may cause
 // the error within this block
 try
 {
 // Use the Point structure to draw lines
 Point pt1 = new Point(30, 40);
 Point pt2 = new Point(250, 60);
 g.DrawLine(redPen, pt1, pt2);
 // Draw a rectangle
 Rectangle rect =
 new Rectangle(20,20, 80, 40);
 g.DrawRectangle(bluePen, rect);
 // Create points for curve
 PointF p1 = new PointF(40.0F, 50.0F);
 PointF p2 = new PointF(60.0F, 70.0F);
 PointF p3 = new PointF(80.0F, 34.0F);
 PointF p4 = new PointF(120.0F, 180.0F);
 PointF p5 = new PointF(200.0F, 150.0F);
 PointF p6 = new PointF(350.0F, 250.0F);
 PointF p7 = new PointF(200.0F, 200.0F);
 PointF[] ptsArray =
 {
 p1, p2, p3, p4, p5, p6, p7
 };
 // Draw Bézier curve
 g.DrawBeziers(redPen, ptsArray);
 }
 catch(Exception exp)
 {
 string errMsg = "Message: " + exp.Message;
 errMsg += "Source: "+ exp.Source.ToString();
 errMsg += "TargetSite: "+ exp.TargetSite;
 errMsg += "HelpLink: "
 + exp.HelpLink.ToString();
 errMsg += "StackTrace: "
 + exp.StackTrace.ToString();
 MessageBox.Show(errMsg);
 }
 finally
 {
 // Release resources
 // Dispose of objects
 redPen.Dispose();
 bluePen.Dispose();
 greenPen.Dispose();
 greenBrush.Dispose();
 g.Dispose();
 }
}

A.2.3 Nested try...catch Statements

We can provide more specific error handling by nesting try...catch blocks. The only case in which we might not want to use nested try...catch blocks is when we want to catch different types of exceptions. For example, one block might catch memory-related exceptions; another, I/O-related exceptions; and a third, general exceptions.

Listing A.6 uses nested try...catch statements. In this code we create two images. The first image we draw only once, but the second image we draw 15 times at different locations. The first try...catch statement covers the entire code with a general exception, and the second try...catch statement is specific to the OutOfMemory exception. We can use as many try...catch blocks as exceptions we want to catch. For example, if our code performs I/O operations, we may want to use the IOException class. We can also customize the default message to match the error type.

Listing A.6 Nesting try...catch statements

private void NestedMenu_Click(object sender,
 System.EventArgs e)
{
 // Create Graphics object
 Graphics g = this.CreateGraphics();
 g.Clear(this.BackColor);
 try
 {
 // Create an image from a file
 Image curImage = Image.FromFile("roses.jpg");
 // Draw the image
 g.DrawImage(curImage, AutoScrollPosition.X,
 AutoScrollPosition.Y,
 curImage.Width, curImage.Height );
 // Create a second image from a file
 Image smallImage =
 Image.FromFile("smallRoses.gif");
 // Draw the second image many times
 int x1, y1, x2, y2, w, h;
 x1 = x2 = AutoScrollPosition.X;
 y1 = AutoScrollPosition.Y;
 y2 = 300;
 w = 20;
 h = 20;
 // Make a loop to draw second image
 // on top of the first image
 for(int i=0; i<=15; i++)
 {
 try
 {
 // Draw from top left to bottom right
 g.DrawImage(smallImage,
 new Rectangle(x1, y1, w, h),
 0, 0, smallImage.Width,
 smallImage.Height,
 GraphicsUnit.Pixel );
 // Draw from top right to bottom left
 g.DrawImage(smallImage,
 new Rectangle(x2, y2, w, h),
 0, 0, smallImage.Width,
 smallImage.Height,
 GraphicsUnit.Pixel );
 x1 += 20;
 y1 += 20;
 x2 += 20;
 y2 -= 20;
 }
 catch (OutOfMemoryException memExp)
 {
 MessageBox.Show(memExp.Message);
 }
 }
 }
 catch(Exception exp)
 {
 MessageBox.Show(exp.Message);
 }
 finally
 {
 // Dispose of objects
 g.Dispose();
 }
}

A.2.4 Multiple catch Statements with a Single try Statement

The try...catch statement also allows us to use multiple catch statements with a single try statement, which helps when we're catching multiple types of exceptions and customizing error messages to match the type of error.

Listing A.7 is a modified version of Listing A.6 that uses a try statement with two catch statements.

Listing A.7 Using multiple catch statements with a single try statement

private void MultiCatchesMenu_Click(object sender,
 System.EventArgs e)
{
 // Create a Graphics object
 Graphics g = this.CreateGraphics();
 g.Clear(this.BackColor);
 try
 {
 // Create an image from a file
 Image curImage = Image.FromFile("roses.jpg");
 // Draw image
 g.DrawImage(curImage, AutoScrollPosition.X,
 AutoScrollPosition.Y,
 curImage.Width, curImage.Height );
 // Create a second image from a file
 Image smallImage =
 Image.FromFile("smallRoses.gif");
 // Draw the second image many times
 int x1, y1, x2, y2, w, h;
 x1 = x2 = AutoScrollPosition.X;
 y1 = AutoScrollPosition.Y;
 y2 = 300;
 w = 20;
 h = 20;
 // Make a loop to draw second image
 // on top of the first image
 for(int i=0; i<=15; i++)
 {
 // Draw from top left to bottom right
 g.DrawImage(smallImage,
 new Rectangle(x1, y1, w, h),
 0, 0, smallImage.Width,
 smallImage.Height,
 GraphicsUnit.Pixel );
 // Draw from top right to bottom left
 g.DrawImage(smallImage,
 new Rectangle(x2, y2, w, h),
 0, 0, smallImage.Width,
 smallImage.Height,
 GraphicsUnit.Pixel );
 x1 += 20;
 y1 += 20;
 x2 += 20;
 y2 -= 20;
 }
 }
 catch (OutOfMemoryException memExp)
 {
 MessageBox.Show(memExp.Message);
 }
 catch(Exception exp)
 {
 MessageBox.Show(exp.Message);
 }
 finally
 {
 // Dispose of objects
 g.Dispose();
 }
}

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