Handling Exceptions

Structured exception handling is based around the idea that while exceptions should be used for unexpected conditions, they can be built within your application structure. Some older languages would allow for generic error handling that didn't exist within a defined set of boundaries. However, professional developers learned long ago that even unexpected conditions should be definable within your application structure.

To allow for this you may have what is known as a last-chance error handler at the topmost level of your application; however, most error handling is structured within individual modules. Within Visual Basic error handling depends on four keywords. Three of these are associated with properly identifying and handling exceptions, while the fourth is used when you wish to signal that an unexpected condition has occurred.

1. Try—Begins a section of code in which an exception might be generated from a code error. This section of code is often called a Try block. It is always used with one or more exception handlers.
2. Catch—Creates a standard exception handler for a type of exception. One or more Catch code blocks follow a Try block. Each Catch block must catch a different exception type. When an exception is encountered in the Try block, the first Catch block that matches that type of exception receives control. Can be omitted when a Finally block is used.
3. Finally—A handler that is always run as part of your structured exception handling. Contains ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.