devxlogo

Use the Err.GetException method to create custom exceptions

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 SubErrorHandler:    ' Add here clean up code as necessary.    ' ...    ' Then report the error to the caller as an Exception object.    Throw Err.GetExceptionEnd Sub

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist