shaminda
October 10th, 2001, 11:50 AM
I have a program that has around 20 functions. For every function I have to copy and paste the same error messages. Is there a way I can reuse the error messages without pasting them in every function over and over? I thought about classes but I don’t know how to do it. Any suggestion would be appreciated.
Cakkie
October 10th, 2001, 12:22 PM
Classes are good, I've used classes for this purpose before. We just created a class, which had a sub called ShowMessage, which took an id, errornumber and description. In the sub, we just took the ID, checked to see if it was a known error, if so, we showed or message, if not, we showed the number and message passed to the sub. It looked something like this:
' class clsErrHandler
public Sub ShowMessage(ID as long, optional ErrNo as Long=0, optional ErrDesc as string="")
Select Case ID
Case 1
strMessage = "error 1 occured"
Case ... '
Case else
strMessage = "Following unknown error occured:" & vbcrlf & ErrNo & vbcrlf & ErrDesc
End Select
Msgbox strMessage, vbCritical, "error"
End Sub
'
'
' When the program started, we declared a public instance of our class
set ErrHandler = new clsErrHandler
'
'
' When we needed it
private Sub TestErrHandler
on error Goto Err_Handler
Dim A as Integer
A = 1 / 0
Exit Sub
Err_Handler:
Select Case Err.Number
Case 1
ErrHandler.ShowMessage 1
Case else
ErrHandler.ShowMessage 0, Err.Number, Err.Description
End Select
End Sub
Ok, this also implies you having to put errorhandling in every sub, but you won't have to retype all the messages, and if you change a message, it is changed everywhere, which doesn't require you to replace it all over the project.
Tom Cannaerts
slisse@planetinternet.be
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning -- Rich Cook
DSJ
October 10th, 2001, 01:06 PM
Another good reason for doing something like what you all are talking about is in your ShowMessage sub you can also write the errors to a log file so when users "don't remember the exact error" or in cases where the users simply ignore the error, you'll have your own record of it.
Cimperiali
October 11th, 2001, 03:51 AM
'You may also call in your error hanlder routine a public function of a bas
'module (this will not prevent you from writing at least 5 sentences in each
'sub or function)
ie:
private sub mySub()
on error goto errHandler
...
...
exit_from_here:
...
exit sub
errHandler:
msgbox myPublicFunctionShowMyMessage(err.number,err.description)
resume next 'or resume exit_from_here or what you want,
'but resume something!
end sub
Special thanks to Lothar "the Great" Haensler, Tom Archer, Chris Eastwood, TCartwright, Bruno Paris, Dr_Michael
and all the other wonderful people who made and make Codeguru a great place.
Come back soon, you Gurus.
The Rater