Advertisment

Structured Exception Handling 

author-image
PCQ Bureau
New Update

Let’s continue from where we left off in last month’s article on advanced VB.NET. In good old VB, exceptions were handled using the On Error Goto statement. It is best not to use legacy features like GoTo/GoSub as they have been removed from VB.NET. There is a much better and structured manner of handling exceptions in VB.NET. Now, you can actually catch and handle exceptions in VB.NET just like you can in C# or Visual C++. It now provides you with the Try-Catch-Finally statement to handle exceptions.

Advertisment

VB.NET finally supports Structured Exception Handling for dealing with common errors. When an operation raises an exception, the caller may handle it or propagate it. Exceptions are instances of classes that derive from System.Exception. System-generated exceptions derive from System.SystemException and Application-specific exceptions derive from

System.ApplicationException.

Raising exceptions



Exceptions are raised implicitly by the runtime or explicitly by the Throw statement. The runtime signals abnormal conditions by raising exceptions. The .NET framework classes signal abnormal conditions using an explicit Throw statement. Your methods may raise exceptions using the Throw statement also. The Throw statement requires an object to be

System.Excpetion.

Catching exceptions



Exceptions are caught by language-specific constructs. VB.NET gives the Try-Catch-Finally statement. Try-Catch protects Try-block with one or more exception handlers. Exception handlers are selected based on exception types. Handled exceptions do not propagate beyond the Try-Catch statement. Unhandled exceptions propagate to the next Try-Catch statement in scope. Listing 9 (on December 2002 CD) shows an example of using a Try-Catch statement. And you can catch multiple exceptions with declarations as shown in Listing 10.

Advertisment

Termination handlers



Sometimes, you need to do some final tasks as part of a cleanup process, no matter what exception is raised. These are referred to as Termination Handlers. These can be expressed using Try-Finally or Try-Catch-Finally statements. It allows cleanup code to run when exceptions are raised. It also allows clean-up code to run when multiple Return statements are used. Listing 11 (shows how to use a Try-Finally statement. Try-Catch-Finally revisited, Listing 12 shows how to combine all of these.

User-defined exceptions



You can define your own exceptions based on various conditions in your application. The only requirement is that your exception class must derive from System.ApplicationException. Listing 13 shows how you can create and use your own exceptions.

Ajay J Singala, Synergetics

Advertisment