Caché ObjectScript Try-finally equivalent

I'm looking for equivalent semantics for the popular Try-finally exception cleanup pattern, eg. Why use try ... finally without a catch clause?

The idea is that you have cleanup steps that must be performed regardless of whether the code runs or fails, but the cleanup code should not interfere with reporting and error handling. Something went wrong and the exception should still propagate.

I would like to write something like this:

O TempFile:(/NEW:/WRITE:/STREAM)
U TempFile
L +LockName
TRY {
 ...code that uses TempFile and may throw an error
} FINALLY {
 //Be sure to delete file whether we have an error or not
 O TempFile:(/DELETE)
 C TempFile
 //Be sure to release lock
 L -LockName
}
... Rest of code that should only execute if there was no error

      

But the TRY ... CATCH syntax in ObjectScript does not support the FINALLY clause.

In particular, it's important that both of these things are typically done with finally blocks:

  • The cleanup code always runs before execution returns to the caller, both when an error occurs and during normal operation.
  • If an error occurs, the original error with its code location, context, and stack will initiate a call stack for the original caller. The cleanup code shouldn't interfere with debugging.

I can't just use a regular TRY ... CATCH block, because the CATCH will have an exception and terminate the correct error context due to chain passing. Maybe there is a way to rethrow the original exception without messing up the error context?

+3


source to share


2 answers


you can throw to catch the error and it will be the original error, with the original error location and something else, so the Try-finally might look like this.



try {
    // some code that could be with errors
} catch ex {
}
// finally

throw:$g(ex) ex
// rest code that can't execute if was error

      

+1


source


Wouldn't it be easier to write the GoTo command in a TRY and CATCH block. If the CATCH block contains a GOTO command, control flows directly to the specified location. This location can act as a Finally block and perform cleanup steps.

An example would look something like this:



try {
    // some code that could be with errors
   GOTO xxx , 'This is the last statement of TRY block
} catch ex {
    //Handle the error
   GOTO XXX
}

XXX
  'your clean up steps

      

0


source







All Articles