Try/Catch¶
See Also: Error System, Error command, UserError, Error numbers, cBaseErrorHandler
Purpose¶
Handles errors reported while a protected block runs.
Syntax¶
Try
// protected statements
Catch [iErrNum] [sErrText]
// error handling statements
End_Try
How it works¶
- Statements inside
Tryrun normally until they finish or an error is reported. - If no error is reported,
Catchis skipped and execution continues afterEnd_Try. - If runtime code, package code, a called procedure/function, or an explicit
Errorcommand reports an error while theTryblock is active, the remainingTrystatements are skipped and control moves toCatch. Catchmay omit variables, receive only the error number withCatch iErrNum, or receive both the error number and text withCatch iErrNum sErrText.- After the
Catchblock finishes, execution continues afterEnd_Tryunless theCatchblock reports another error. - Nested
Try/Catchblocks handle errors at the nearest activeCatch; aCatchcan report/re-raise an error when an outer handler or caller still needs to see it.
When to use it¶
Use Try/Catch when code can recover locally, translate the error to a user-facing message, clean up and continue, or clean up and re-report the error.
Do not use Try/Catch to silently swallow an error unless the invalid condition is fully handled.
Try/Catch versus Error¶
Try/Catch handles an error that occurs in a block.
Error reports a new error at the point where code detects an invalid condition.
Try/Catch does not create errors by itself, and Error does not recover from errors.
Example: handle locally¶
Procedure SaveCustomer String sCustomerName
Try
If (sCustomerName = "") Begin
Error DFERR_OPERATOR "Customer name is required."
End
Send DoSaveCustomer sCustomerName
Catch iErrNum sErrText
Send UserError sErrText "Save failed"
End_Try
End_Procedure
The empty name is reported with Error; Catch receives the error number and text, then converts the failure to a user-facing message.
Example: clean up and re-report¶
Try
Send DoWork
Catch
Send DoCleanup
Error Last_Error_Number ErrText
End_Try
Cleanup runs in Catch; Error Last_Error_Number ErrText reports the caught error again so the caller's error handler can still see it. This mirrors the existing transaction command documentation pattern.