You will have to create your own error classes to handle a maximum length exception and a zero-length string exception.
Note | Microsoft has developed a set of exception handling libraries called the Exception Management Application Block. But a set of libraries is really just scratching the surface. It is a set of code you can also use to implement your own exception classes, and it is designed as a frame-work. Microsoft also includes the source code and best practices for its use. If you are creating large-scale applications or a repository of enterprise application errors, this is probably a good source of code and/or information. |
To begin, add a new class module to the NorthwindShared project and call it Errors. Delete the class declaration that is added by default and add the code in Listing 5-1.
Listing 5-1: The MaximumLengthException Class
Option Strict On Option Explicit On Namespace Errors Public Class MaximumLengthException Inherits ApplicationException Public Sub New(ByVal MaxLength As Integer) MyBase.New("The maximum length for this value is " _ & MaxLength.ToString & " characters.") End Sub End Class End Namespace
All of your custom errors will be placed in the Errors namespace so that you can find them easily. Here you are creating an exception class called MaximumLengthException using .NET's exception naming standards (the error name followed by the word Exception). Your constructor accepts the maximum length you are allowing for the rule and creates a message to pass in to the base class constructor. This exception is now reusable by any piece of data that might violate this rule. Now you need to add one more exception to catch zero-length strings (empty strings). To do this, enter the following code in the Errors namespace:
Public Class ZeroLengthException Inherits System.ApplicationException Public Sub New() MyBase.New("A value must be entered for this item.") End Sub End Class