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

Types

Description

System.ApplicationException

An application-specific exception occurred.

System.ArgumentException

An argument is invalid.

System.ArgumentNullException

An argument is Nothing .

System.ArgumentOutOfRangeException

An argument was not within its valid range.

System.DivideByZeroException

An operation divided by zero.

System.DllNotFoundException

The Lib clause of a Declare statement was not found.

System.ExecutionEngineException

The .NET Framework encountered an internal error.

System.InvalidCastException

A conversion from one type to another was not valid.

System.NotSupportedException

The method is not supported.

System.NullReferenceException

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

System.OutOfMemoryException

The program has run out of memory.

System.OverflowException

An operation overflowed.

System.Runtime.InteropServices.COMException

An exception occurred while a COM object was being called.

Compatibility

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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net