xHarbour Reference Documentation > Statement Reference xHarbour Developers Network  

TRY...CATCH

Declares a control structure for error handling.

Syntax

TRY
 <statements>
 [THROW( <oErrorObject> )]
 [CATCH [<thrownError>]
   <errorHandling>
 [FINALLY
  <guaranteed> ]
END

Arguments

<statements>
These are the regular programming statements to execute in the TRY...CATCH control structure.
THROW <oErrorObject>
When an unexpected situation is detected in <statements>, a new Error object can be created explicitly and passed to the Throw() function. If <oErrorObject> is omitted and an error is detected by the xHarbour runtime, the Error object is created automatically.
CATCH <thrownError>
This is an optionally declared variable that receives the error object passed to the Throw() function in the TRY section of the control structure.

The statements following the CATCH clause are used for error handling.

FINALLY
The finally section is guaranteed to be executed, no matter if an error was handled or not.

Description

Any code that might throw an exception is placed inside of the try block. If an exception is thrown, the catch block is entered and the program can perform the appropriate operation to recover or alert the user.

If FINALLY is specified, code within the FINALLY section is guranteed to be executed after the TRY section has been executed and the CATCH section is activated, unless the CATCH section throws an UNHANDLED Error. This means that the FINALLY section will be executed even if the CATCH section re-throws the error or attempts to RETURN. In such cases, the requested operation which forces out of the TRY section will be deferred until after the FINALLY section has been completed.

Important:  although CATCH and FINALLY are both marked as optional, at least one of these options must be used within a TRY...END control block.

Info

See also:BEGIN SEQUENCE, Error(), ErrorBlock(), ErrorNew(), Throw()
Category: Control structures , Statements , xHarbour extensions

Example

// The example demonstrates program flow for a TRY..CATCH sequence

   PROCEDURE Main()
      LOCAL oErr

      TRY
        ? "Trying"
        ? "Throwing"
        Throw( ErrorNew( "Finalize Test", 0, 0, "Forced Error" ) )

      CATCH oErr
        ? "Caught:", oErr:Operation
        ? "Throwing to outer, should be deferred"
        Throw( oErr )
      FINALLY
         ? "Finalized"
      END

      ? "Oops, should have Re-Thrown, after the FINALLY."
   RETURN

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe