Skip to content

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 Try run normally until they finish or an error is reported.
  • If no error is reported, Catch is skipped and execution continues after End_Try.
  • If runtime code, package code, a called procedure/function, or an explicit Error command reports an error while the Try block is active, the remaining Try statements are skipped and control moves to Catch.
  • Catch may omit variables, receive only the error number with Catch iErrNum, or receive both the error number and text with Catch iErrNum sErrText.
  • After the Catch block finishes, execution continues after End_Try unless the Catch block reports another error.
  • Nested Try/Catch blocks handle errors at the nearest active Catch; a Catch can 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.

See also