Exception Handling

The common language runtime provides an exception notification service so that it's easy to determine that an error has occurred. The .NET Framework provides a number of exception classes that describe the most common types of exceptions. With managed code, you should use structured exception handling—such as Try Catch Finally (Try Catch) statements—to check whether an exception is thrown within your code and handle the exception accordingly. Rather than use the method of error handling used in VBA code (On Error GoTo statements), you should instead favor the more robust exception handling of a Try Catch statement.

A Try Catch statement is made up of a Try block, a Catch block, and an End Try statement. You add the code that can possibly cause an exception in the Try block as a way to "try out" the code. Then you "catch" any exceptions that are thrown by handling the exception in the Catch block.

If needed, you can break out of a Try Catch statement by using the Exit Try keyword. The Finally block is always executed, whether or not an error is raised and handled.

You end a Try Catch statement with End Try. For example, the code in Listing 3.13 shows how you can check whether a folder exists. The code sets a folder named Personnel as the current Outlook folder in a Try block and displays an error in the Catch block if an exception is raised. An exception is raised if inbox.Folders does not contain an entry for "Personnel." Note, however, that it is better to specify the type of exception in the Catch statement (if it is known) than to catch all exceptions as in this example.

Listing 3.13. Try Catch statement Try

Me.ActiveExplorer().CurrentFolder = inBox.Folders( _ "Personnel") Catch Ex As Exception MsgBox(Ex.Message) End Try

0 0

Post a comment