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. ...

Get Programming Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.