Reputation: 8131
small question, in Visual Basic 6.0 (VB6)
Assuming I missed a possible situation and the user did something and did not expect, then he gets an error that crashes my application. Is there an event I can work with that will execute a certain code if that happens ?
Tried Form_Terminate \ Unload \ Query_Unload, not much luck there.
Crash: AKA Run-Time Error.
Upvotes: 1
Views: 151
Reputation: 7093
You can add an On Error
check at any level, including your Sub Main
. Any errors that are not caught by an error check at that functions level will rise through the call stack to the main/initial method where you could there catch them.
You could then gracefully display the error (so you or your users are aware of it) and then resume whatever method is best at that point. And, remember, you can do this at several different strategic levels and locations.
If the errors occur in an event procedure, then these won't be trapped in Sub Main()
so you will also need to catch them there.
Any errors that rise to the top of the stack, either out of Sub Main()
or an event procedure will be caught by the runtime and are fatal. Your code will get no notification of this.
You may also be interested in the post Good Patterns For VBA Error Handling.
Upvotes: 2
Reputation: 7699
On the the frequent ways to capture error in VB6, is by using the On Error
and the GOTO
tags. At the beginning of each Function, you just declare the goto in case of error, and whenever an error arises, the GOTO part will be executed.
Note that the Goto part should go at the end of the method, so as after running the codes, no other piece of code is executed but leave the Function. Check the example below;
Private Function MyMethod()
Dim sMsg As String
On Error Goto ErrHandler
' ...code here...
Exit Function
ErrHandler:
sMsg = "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
GoLogTheError sMsg
End Function
Upvotes: 0