Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB.NET
Expertise: Intermediate
Nov 24, 2001

Use the Err.GetException method to create custom exceptions

The Visual Basic .NET Err.Raise method and the Throw command are (partially) compatible. For example, you can use a Try...End Try block to catch an error raised with the Err.Raise method, and you can use an On Error Resume Next and the Err object to neutralize and inspect an exception object created by the Throw command. The old and the new error trapping mechanisms don't coexist well, though, and there are a few limitations. For example, you can't have an On Error Resume Next statement and a Try...End Try block in the same procedure.

To assist you in porting existing applications to VB.NET, the Err object has been extended with the new GetException method, which returns the Exception object that corresponds to the current error. This feature lets you preserve old-style error handlers in those procedures that don't lend themselves to an easy porting to the new syntax. This new method also enables such procedures them to correctly throw an exception object to their caller, where the exception can be processed using a Try block as usual:


Sub OldStyleErrorHandlerProc()
    On Error Goto ErrorHandler

    ' Cause a division by zero error,
    Dim x, y As Integer
    y = 1 \ x
    Exit Sub

ErrorHandler:
    ' Add here clean up code as necessary.
    ' ...
    ' Then report the error to the caller as an Exception object.
    Throw Err.GetException
End Sub
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date