Throwing Exceptions

 <  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




An application-specific exception occurred.


An argument is invalid.


An argument is Nothing .


An argument was not within its valid range.


An operation divided by zero.


The Lib clause of a Declare statement was not found.


The .NET Framework encountered an internal error.


A conversion from one type to another was not valid.


The method is not supported.


The program tried to use a Nothing value in an invalid way.


The program has run out of memory.


An operation overflowed.


An exception occurred while a COM object was being called.


Exceptions can also be thrown using the Error statement. The Error statement takes an error number as an argument instead of an exception object. This is a holdover from previous versions of the Visual Basic language, where exceptions were thrown by number instead of by type. In Visual Basic .NET, the error number is translated into the appropriate exception type, and then a new exception of that type is thrown. Use of the Error statement is strongly discouraged.

 <  Day Day Up  >  

The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: