Error handling code problem

ijswalker

Registered User.
Local time
Today, 15:21
Joined
Jun 16, 2008
Messages
67
I am trying to get this code to work but I seem to have something missing and I can't figure it out. I am trying to check it in the immediate window of the Visual Basic Editor and I keep getting a compiling error. I use the TestError (5,0) as my test.

Thanks

Ian

Code:
Sub TestError(intValue1 As Integer, intValue2 As Integer)
On Error GoTo HandleError
'declare variable to store result
Dim intResult As Integer
'calculate result by dividing first value by second value
intResult = intValue1 / intValue2
Exit Sub
HandleError:
    MsgBox "Error has occurred in your application: " & Err.Description
    Exit Sub
    
End Sub
 
Maybe you shouldn't supply brackets () around parameters for a call that does not return a value?

Code:
SomeSub Param1, Param2
 - vs -
Result = SomeFunction(Param1, Param2)
 
Thanks lagbolt, you are right on the money.

Ian
 
I'm having an issue with the same code. I should get "An error has occurred in your application: Division by zero" but instead I'm getting a "Runtime Error 11, Division by zero". I'm using the same code exactly as it is in the book. Can't figure it out?



Code:
Sub TestError(intValue1 As Integer, intValue2 As Integer)
    
    On Error GoTo HandleError
    
        'declare variable to store result
        Dim intResult As Integer
        
        'calculate result by dividing first value by second value
        intResult = intValue1 / intValue2
        
    Exit Sub
    
HandleError:
    MsgBox "An error has occurred in your application: " & Err.Description
    Exit Sub
    
    End Sub
 
of course - if intvalue2 is 0, the calculation cannot be made, and causes the run time error - since anything divided by 0 is infinity (error)

note also that dividing two integers rarely produces an integer result - if you do want an integewr result you should be careful to understand the rounding that will be applied.
 
You can set Visual Basic to break on all errors or to break for errors in class modules. With either setting you can have errors that occur within the scope of an enabled error handler and still, perhaps unexpectedly, break into the debugger.
In a code window check Tools->Options->General Tab->Error Trapping Section. Make sure the 'Break on Unhandled Errors' is selected.
 

Users who are viewing this thread

Back
Top Bottom