Chapter 15. Exceptions

Introduction

Visual Basic has included error handling since its initial release through the On Error statement. Although often derided by developers, this mechanism did effectively catch and process all errors when used properly. Visual Basic 2005 still includes this error-handling methodology, but it also includes structured error handling, new with .NET. This chapter considers this new error-processing system, comprised of the Try…Catch…Finally statement and System.Exception-derived error objects.

15.1. Catching an Exception

Problem

Although you’ve been a Visual Basic 6.0 developer for years, and you’ve already used On Error statements in your Visual Basic 2005 code, you want to try out the structured error-handling statements you’ve heard so much about.

Solution

Use the Try…Catch…Finally block statement to locally monitor and handle errors. The statement has three sections:

Try

The code you need to monitor for errors appears in this first section.

Catch

When an error occurs, processing jumps immediately from the Try section to a matching Catch block (We’ll define “matching” shortly). Any remaining unprocessed statements in the Try block are ignored. You can have any number of Catch entries in your error-handling block.

Finally

Any code you include in this optional section runs whether an exception occurs or not. It’s a useful place to put any cleanup code related to resources you allocated in the Try section.

Here’s the syntax of the Try…Catch…Finally statement:

 Try ...

Get Visual Basic 2005 Cookbook 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.