exception handling strategy

davidrobin

Freshman
Joined
Jun 24, 2003
Messages
41
:) Hi all,

I posted on the forums sister site relating to error handling and VB6.

As I am attempting to develop VB6 applications that can be easily ported to vb.net (also the fact that I am new to VB.net) how can I use a similar method to the example below for error handling.

I am aware you don't have error handling in .net but exception handling instead.

class could look something like this:
Visual Basic:
Option Explicit

Dim m_Number As Long

Public Sub RaiseErr(funcName As String, errNum As Long, errDesc As String, passError As Boolean)
    If (errNum <> 1001) Then
        'Save and log the error
        m_Number = errNum
        Debug.Print "Error raised in " & funcName & ":"
        Debug.Print errNum & " : " & errDesc
    End If
    'Pass error up to next object
    If (passError) Then Err.Raise 1001
End Sub

Public Property Get Number() As Long
    Number = m_Number
End Property

In raise error where it says 'save and log the error, at this point the error will be stored in a database table, the main reason for creating the strategy.


And your main code like this:

Visual Basic:
Option Explicit

'Module level error object
Dim errObj As cError

Private Sub Form_Load()
    Set errObj = New cError
End Sub
Private Sub Command1_Click()
    On Error Goto Abort

    Func1
    Exit Sub
Abort:
    errObj.RaiseErr "Command1_Click()", Err.Number, Err.Description, False
    If (errObj.Number = 11) Then
        MsgBox "Please do not divide by zero, thankyou"
    Else
        MsgBox "An unexpected error occurred"
    End If
End Sub

Private Sub Func1()
    On Error Goto Abort

    Func2
    Exit Sub
Abort:
    errObj.RaiseErr "Func1()", Err.Number, Err.Description, True
End Sub

Private Sub Func2()
    On Error Goto Abort

    Func3
    Exit Sub
Abort:
    errObj.RaiseErr "Func2()", Err.Number, Err.Description, True
End Sub

Private Sub Func3()
    On Error Goto Abort

    Dim i As Long
    i = 1 / 0
    Exit Sub
Abort:
    errObj.RaiseErr "Func3()", Err.Number, Err.Description, True
End Sub
 
So, what's the question?

You can raise an error like this:
Visual Basic:
Throw New Exception("Text here")
you can also create your own exceptions, and catch them. Create a class called MyException that inherits Exception, then you can do this:
Visual Basic:
Throw New MyException("My Exeption!")
You catch them like this:
Visual Basic:
Try
  'code that may cause an error here
Catch me As MyException
  'this will catch all 'MyExceptions' that were raised
Catch e As Exception
  'this will catch all other exceptions
End Try
 
Back
Top