Log in

View Full Version : Error handling in functions



Jfp87
03-10-2017, 09:35 AM
Guys,

I have a question about error handling in simple functions like the following:


Function fcnGetToken(str As String, strDelimiter As String, lngTokenNumber As Long) As String
'Function to return a token from a delimited string (1-based).
'E.g. fcnGetToken("14|Hello world!|123", "|", 2) = Hello world!
Dim strToken As String
'Ensure string has been supplied
Debug.Assert Len(str) > 0
'Ensure delimiter has been supplied
Debug.Assert Len(strDelimiter) > 0
'Ensure delimiter exists in string
Debug.Assert InStr(str, strDelimiter) <> 0
'Ensure lngTokenNumber exists in string
Debug.Assert (lngTokenNumber - 1) <= UBound(Split(str, strDelimiter))
strToken = Split(str, strDelimiter)(lngTokenNumber - 1) 'Split() is zero-based
fcnGetToken = strToken
lbl_Exit:
Exit Function
End Function

Say I have been using the Debug.Assert statements throughout testing to ensure that accepted values are being fed in, and everything seems fine. If for some reason after testing, when the .Assert statements are turned off, the function accepts a value which is unprepared for and will cause problems down the line - what should the course of action be?

Write an error log and stop execution?

Joe

SamT
03-10-2017, 11:33 AM
As written, the Function declaration itself will return an error if any parameter is not present.

All below require

Exit Function
ErrHandler:
MsgBox ErrMsg
End Function


'Ensure delimiter exists in string
If Instr(Str, Delimiter) = 0 Then
ErrMsg = "The delimiter is not found in the input string"
Goto ErrHandler
End if


'Ensure lngTokenNumber exists in string
If (lngTokenNumber - 1) < UBound(Split(str, strDelimiter)) then
ErrMsg = "The Token number is too big"
Goto ErrHandler
End if

gmaxey
03-10-2017, 12:29 PM
Sub Test()
MsgBox fcnGetToken("A|B|C|D", 2)
MsgBox fcnGetToken("A|B|C|D", 7)
MsgBox fcnGetToken("A|B|C|D", 1, "*")
End Sub
Function fcnGetToken(str As String, lngTokenNumber As Long, Optional strDelimiter As String = "|") As String
On Error GoTo Err_Handler
If InStr(str, strDelimiter) > 0 Then
fcnGetToken = Split(str, strDelimiter)(lngTokenNumber - 1)
Else
Err.Raise 5
End If
lbl_Exit:
Exit Function
Err_Handler:
Select Case Err.Number
Case 9
fcnGetToken = "Token number out of range"
Resume lbl_Exit
Case 5
fcnGetToken = "Argument (delimiter) not valid"
Resume lbl_Exit
Case Else
'As required
End Select
End Function

Jfp87
03-12-2017, 12:06 PM
SamT, Greg...thanks for that.