Recipe 15.2. Throwing an Exception


Problem

An invalid condition has occurred in your custom class code, and you want to generate an exception to inform the calling code of the problem.

Solution

Use the Throw statement to send an exception to the next available error handler. THRow takes an instance of a System.Exception (or derived) object as its only argument:

 Throw New System.Exception("A great big error occurred.") 

You can also prepare your exception object in advance and then use its variable in the Throw statement:

 Dim errorDetail As New System.ArgumentOutOfRangeException( _    "Year", "The 'Year' must be at least 1995.") Throw errorDetail 

Discussion

When .NET detects an error in your program, it also uses the Throw statement to send errors to your code. When you use the THRow statement, your generated errors look just like those issued by the Framework.

You can generate an error at any time using the Throw statement, even within a try block. The related Catch handler will process the error as if some other system-defined process had generated the error.

Visual Basic also includes an Err.Raise method that generates errors, as was done using pre-.NET versions of Visual Basic. It focuses on error numbers rather than on object-based exceptions. Although .NET will wrap errors issued through Err.Raise in an Exception object, you should use this method only for backward compatibility. Use the Throw statement instead.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

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