Caché Basic Reference
Try
[Back] [Next]
   
Server:docs2
Instance:LATEST
User:UnknownUser
 
-
Go to:
Search:    

Identifies a block of code to monitor for errors during execution.
Synopsis
Try
   statements
Catch [exceptionvar]
   statements
End Try
Description
The Try command takes no arguments. It is used to identify one or more Caché Basic code statements between the Try keyword and the Catch keyword. This block of code is protected code for structured exception handling. If an exception occurs within this block of code, Caché sets Err, then transfers execution to an exception handler, identified by the Catch command. This is known as throwing an exception. If no error occurs, execution continues with the next Caché Basic statement after the End Try statement.
An exception may occur as a result of a runtime error, such as attempting to divide by 0, or it may be explicitly propagated by issuing a Throw command.
A Try block must be immediately followed by a Catch block. The paired Try and Catch are terminated by an End Try statement.
Examples
In the following examples, the Try code block is executed. It attempts to set the local variable a. In the first example, the code completes successfully, and the Catch is skipped over. In the second example, the code fails an Err error indicating division by zero, and execution is passed to the Catch command.
Try succeeds:
  Try 
    SET x=2
    PRINTLN "about to divide by ",x
    SET a=7/x
    PRINTLN "Success: the result is ",a
  Catch myvar 
    PRINTLN "this is the exception handler"
    PRINTLN "Error number: ",Err.Number
    PRINTLN "Error is: ",Err.Description
    PRINTLN "Error code: ",myvar.Code
  End Try
  PRINTLN "this is where the code falls through"
 
Try fails:
  Try
    SET x=0
    PRINTLN "about to divide by ",x
    SET a=7/x
    PRINTLN "Success: the result is ",a
  Catch myvar 
    PRINTLN "this is the exception handler"
    PRINTLN "Error number: ",Err.Number
    PRINTLN "Error is: ",Err.Description
    PRINTLN "Error code: ",myvar.Code
  End Try
  PRINTLN "this is where the code falls through"
 
See Also