Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to raise custom exceptions

Status
Not open for further replies.

SkyHigh

Technical User
May 30, 2002
309
CA
Hi Folks

I would like to know how do raise custom exceptions in VBA and halt execution of any subsequent code.

In my case I have various public functions which check for certain information in the database, I am calling these functions from a command button whereever suitable, but what is happening is that whenever these functions find descripencies they display an error msg and exit from their own function but the subsequent code in the command button sub continues to execute, how do I raise an exception in a public function and handle it in a sub which calls this function.

Thanks much for your help
Brenda
 
Hi Brenda,
You can raise a custom error by just using the raise method of the Err Object like this: Err.Raise 8888 However, the error is not global in scope--it only exists for the sub/function where the error occurs, so if you raise a custom error, and check it in your sub, the Err.Number will have been set back to zero. So, you will probably need to be a little more creative.

A fairly simple way to solve your problem is to code an error handler in your function, which causes the function to return a value that indicates to the sub that an error happened in the sub. Of course, the return value will have to be of the correct data type. The sub then checks for the error response after each function call, and if it finds it, exits the sub without running the remainder of the code. Here is a simple example:

Sub mySub()
strABC = GetVal1(myArg1)
If strABC = "ERROR" then Exit Sub

strDEF = GetVal2(myArg2)
If strDEF = "ERROR" then Exit Sub

strGHI = GetVal3(myArg3)
If strGHI = "ERROR" then Exit Sub
.
.
.
End Sub

Public function GetVal1(arg as single) As String
On Error GoTo ErrHandler
'Some logic here to do whatever the function does
'If this logic causes an error we jump to ErrHandler
GetVal1 = whatever

Exit Function

ErrHandler:
Msgbox Err.Number; etc;etc
GetVal1 = "ERROR"

End Function

Hope that helps,
Tranman
 
halt execution of any subsequent code
Take a look at the End instruction.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top