Choosing When to Use Structured and Unstructured Exception Handling (Visual Basic)
Structured exception handling is simply that — using a control structure containing exceptions, isolated blocks of code, and filters to create an exception handling mechanism. This allows your code to differentiate between different types of errors and react in accordance with circumstances. In unstructured exception handling, an On Error statement at the beginning of the code handles all exceptions.
Structured exception handling is significantly more versatile, robust, and flexible than unstructured. If possible, use structured exception handling. However, you might use unstructured exception handling under these circumstances:
You are upgrading an application written in an earlier version of Visual Basic.
You are developing a preliminary or draft version of an application and you don't mind if the program fails to shut down gracefully.
You know in advance exactly what will cause the exception.
A deadline is pressing, you need to take shortcuts, and are willing to sacrifice flexibility for speed.
Code is trivial or so short that you only need to test the branch of code generating the exception.
You need to use the Resume Next statement, which is not supported in structured exception handling.
You cannot combine structured and unstructured exception handling in the same function. If you use an On Error statement, you cannot use a Try...Catch statement in the same function.
Regardless of which you choose to handle exceptions within your code, you must take a step back and examine what assumptions that code makes. For example, when your application asks the user to input a telephone number, the following assumptions come into play:
The user will input a number rather than characters.
The number will have a certain format.
The user will not input a null string.
The user has a single telephone number.
User input might violate any or all of these assumptions. Robust code requires adequate exception handling, which allows your application to recover gracefully from such a violation.
Unless you can guarantee that a method will never throw an exception under any circumstances, allow for informative exception handling. Exception handling should be meaningful. Beyond stating that something went wrong, messages resulting from exception handling should indicate why and where it went wrong. An uninformative message along the lines of "An error has occurred" only frustrates the user.