< Day Day Up > |
Exceptions can be thrown in one of two ways. The recommended way is to create a new exception object and throw it using the Throw statement. The following function throws an exception when the divisor passed in is zero. Function Divide(ByVal x As Integer, ByVal y As Integer) As Integer If y = 0 Then Throw New ArgumentException("y", "Divisor cannot be zero.") End If Return x \ y End Function The argument to a Throw statement must be an instance of System.Exception or an instance of a type that is derived from the type System.Exception (see Chapter 13, Inheritance, for more on derived types). In general, it is important to throw the most specific exception possible to allow callers to handle only errors that they are prepared to deal with. Some of the more common exception types are listed in Table 7-1. New exception types within an application can be created by defining new classes that inherit directly from System.ApplicationException or any type that inherits from System.ApplicationException . Table 7-1. Common Exception Types
|
< Day Day Up > |