Wiki Home

Throw Exception


Namespace: VFP
VFP8's Try Catch feature includes the ability to THROW an exception.

THROW is alot like the ERROR command, except that ERROR allows you to pass a string, and THROW lets you pass any type of data along. When the exception is caught, that data is stored in the UserValue property.

Local oEx
Try 

	*I'm going to try to throw an exception
	Throw "The disk is spaced."

Catch To oEx

	Wait WINDOW "Error Message: " + oEx.Message + ;
		Chr(13) + Chr(10) + "User Value: " + oEx.UserValue

EndTry


That's fine, but, I'd prefer to have my value end up in the Message property instead of "User Thrown Error . "

To do that, I created a Throw Exception function (this can be in a global utility file or a standalone PRG, ect)

Function ThrowException(tcMessage, tnErrorNo, tcDetails)
* Throw an error, catch it, modify it, and rethrow it
Local oExp, lnLevel, laStack[1]
Try 
	Throw 
Catch To oExp
	lnLevel				= AStackInfo(laStack) - 1
	oExp.Message		= Evl(tcMessage, "") 
	oExp.ErrorNo		= Evl(tnErrorNo, oExp.ErrorNo) 
	oExp.Details		= Evl(tcDetails, "") 
	oExp.Procedure		= laStack[lnLevel, 3]
	oExp.LineNo			= laStack[lnLevel, 5]
	oExp.LineContents	= laStack[lnLevel, 6]
	oExp.StackLevel		= lnLevel

	Throw 
EndTry 
Return


The single comment explains it all. Now if I change in my original code, the line:

	Throw "The disk is spaced."


to:

	ThrowException("The disk is spaced.")


I should catch an exception object, that looks like the one that would have been thrown, except for the Message property is my custom message (plus I have control over the ErrorNo and Details).

Contributor: Mike Helland

How does THROW compare to ERROR, otherwise? That is, if you use the ERROR command, will CATCH still catch it? (I don't have VFP8 yet to test...) - ?wgcs

Yes.
Very nice Mike. I can use this. - ?lc
Yes, I agree: Nice Work Mike! I wonder why Throw wasn't designed this way to start; At least we can get there with this util. - wgcs
See also Throw Exception Revisited
Category Code Samples Category Error Handling
( Topic last updated: 2003.04.26 08:43:20 AM )