1. Technology

Structured Error Handling


7 of 9

What Could Go Wrong? - A Few Things That Might Be Confusing
Structured Error Handling

Double-click for a larger view.

A potential "gotcha" with Try ... Catch blocks can be illustrated by a modified version of our Divide by Zero example. Suppose you decided to change the program so the values of X, Y, and Z that caused the error would be displayed using the Debug.WriteLine statement. You might try coding it this way:

  ' The traditional Divide By Zero error
  Dim X, Y, Z As Integer
  X = 1 : Y = 0
  Z = X / Y
Catch ex As Exception
  Debug.WriteLine("exception using X, Y, and Z values" _
  & vbCrLf & vbTab & X & Y & Z)
End Try

The illustration shows the syntax error messages. These messages don't point very directly to what's wrong, so let's just get right to the problem. Both the Try and the Catch blocks are separate coding blocks in VB.NET and can't share variables unless you code them to do that. So, because X, Y, and Z are declared in the Try block, they are not available in the Catch block. To solve the problem, just move them outside both blocks. (Before the Try statement.)

  1. About.com
  2. Technology
  3. Visual Basic
  4. Learn VB.NET
  5. Trapping Errors Using Structured Error Handling

©2014 About.com. All rights reserved.