Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Finally Equivalent in Caché ObjectScript

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

The idea is that you have cleanup steps that need to happen regardless of whether the code succeeds or fails, but the cleanup code shouldn't interfere with reporting and handling the error. Something still 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 normally done by finally blocks hold true:

  • The cleanup code is always run before execution is returned to the caller, both when there was an error and when everything ran normally.
  • If an error occurs, the original error with its code location, context and stack are propogated up the call stack to the original caller. The cleanup code shouldn't interfere with debugging.

I can't simply use a regular TRY...CATCH block because CATCH will eat the exception and stop the correct error context from being passed up the chain. Maybe there is a way to re-throw the original exception without messing up the error context?

like image 738
Chris Smith Avatar asked Nov 22 '25 19:11

Chris Smith


1 Answers

you can throw caught error, and it will be original error, with original place of error and anything else, so Try-Finally may looks like below.

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

throw:$g(ex) ex
// rest code that can't execute if was error
like image 140
DAiMor Avatar answered Nov 25 '25 07:11

DAiMor