Skip to Content
Programming Visual Basic .NET
book

Programming Visual Basic .NET

by Dave Grundgeiger
December 2001
Beginner
464 pages
13h 51m
English
O'Reilly Media, Inc.
Content preview from Programming Visual Basic .NET

Exceptions

Sometimes errors or exceptional conditions prohibit a program from continuing its current activity. A classic example is division by zero:

Dim x As Integer = 0
Dim y As Integer = 1 \ x

When the process hits the line containing the integer division, an exception occurs. An exception is any occurrence that is not considered part of normal, expected program flow. The runtime detects, or catches, this exception and takes appropriate action, generally resulting in termination of the offending program. Figure 2-3 shows the message box that is displayed when this code is run within the Visual Studio .NET IDE.

A divide-by-zero exception

Figure 2-3. A divide-by-zero exception

Visual Basic .NET programs can and should be written to catch exceptions themselves. This is done by wrapping potentially dangerous code in Try...End Try blocks. Example 2-9 shows how to catch the divide-by-zero exception.

Example 2-9. Catching an exception

Try
   Dim x As Integer = 0
   Dim y As Integer = 1 \ x
Catch e As Exception
   Console.WriteLine(e.Message)
End Try

When the program attempts the division by zero, an exception occurs, and program execution jumps to the first statement in the Catch block. The Catch statement declares a variable of type Exception that receives information about the exception that occurred. This information can then be used within the Catch block to record or report the exception, or to take corrective action. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Visual Basic .NET, Second Edition

Programming Visual Basic .NET, Second Edition

Jesse Liberty

Publisher Resources

ISBN: 0596000936Supplemental ContentCatalog PageErrata