Raise ERROR to the caller of a user-defined function
- Last Updated: October 18, 2024
- 2 minute read
- OpenEdge
- Version 12.2
- Documentation
Raise ERROR to the caller of a user-defined function
The user-defined function, defined by the FUNCTION statement, returns a value of a specific data type as its primary
function. The RETURN statement is used in the function
body to specify what value to return to the caller. The RETURN
ERROR statement is not used in the same way as it is in other blocks since
it does not raise ERROR in the caller. Instead, it sets
the target variable of the function to the Unknown value (?). Therefore, you can perform error checking on a function call by
checking for the Unknown value (?). This technique only
works if the target variable has a value other than the Unknown value (?) before the function is called.
The following code demonstrates this behavior:
|
If you specify a string (RETURN ERROR
<string>), the string is not seen as a RETURN-VALUE, but as the value being returned from the function.
Therefore, if the function is defined to return a type other than CHARACTER, you get a
compiler error (or a runtime error if the expression type is indeterminate at compile
time). If the function is defined to return a CHARACTER, the code runs, but RETURN-VALUE is not set. The specified string is lost.
Structured error handling provides a more consistent and robust way to raise
ERROR from user-defined functions using the UNDO,
THROW statement rather than RETURN ERROR. There are two
ways to do this:
- Syntactically, you cannot use an
ON ERRORphrase on aFUNCTIONdefinition. Therefore, use theROUTINE-LEVEL ON ERROR UNDO, THROW(orBLOCK-LEVEL ON ERROR UNDO, THROW) statement to set that directive on the function. Then any unexpected error, or explicitly thrown application errors, can be thrown back to the caller. Just be aware that this affects all routines or blocks in the file. - Add a
CATCHblock to the function. With aCATCHblock, any error that is caught can be thrown out of the function using theUNDO, THROWstatement from within theCATCHblock. If you only want to throw application errors back to the caller but handle system errors locally, or vice versa, you can use multipleCATCHblocks to accomplish this. Using multipleCATCHblocks is shown in the example below. To learn more, see CATCH Blocks.
|