Skip to main content
Previous sectionNext section

Throw

Throws an exception from a Try block to a Catch exception handler.

Synopsis

Throw [oref]

Arguments

oref Optional — A user-defined object reference.

Description

The Throw command explicitly issues an exception from within a block of code defined by a Try command. Issuing a Throw transfers execution from the Try block to the corresponding Catch exception handler.

Throw is used to issue an explicit exception. Caché issues an implicit exception when a runtime error occurs. A runtime error generates an exception object which it throws to a Catch exception handler.

Throw has two forms:

  • Without an argument

  • With an argument

Throw without an Argument

Argumentless Throw transfers error processing to the corresponding Catch error handler. No object is pushed on the stack, but the %New() method is called.

Throw with an Argument

Throw oref specifies a user-defined object reference, which it throws to the Catch command, pushing it on the execution stack. The calling of the %New() method is optional.

Arguments

expression

A user-defined object reference (oref). For example, Throw ##class(%Exception).%New(). The creation and population of this exception object is the responsibility of the programmer.

Examples

The following example shows an argumentless Throw:

  Try
    SET x=2
    PRINTLN "about to divide by ",x
  Throw
    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"
Copy code to clipboard

See Also