Discussion
· Jun 13

$ZTRAP vs Try/Throw/Catch

I'm scraping my way through some code that's been around for a while, and came across the use of $ZTRAP and (dear GOD) GOTO for trapping and handling errors.

In an effort to "modernize" it and make it, I don't know, less M-ish (sorry old-timers!), I'm replacing it with Try/Catch blocks.

Some questions:

  1. Is this a dumb idea?
  2. Anything I should look out for?
  3. Did I hurt anyone's feelings?

And if the answer to number 3 is Yes, my deepest apologies ... I love you guys! 🤩

Discussion (5)3
Log in or sign up to continue

It's not a dumb idea, but I would balance the risk you're introducing against the value. Refactor if you're already in the code, but if it ain't broke ...

The main thing to look out for is that the control flow is different. One pitfall of try-catch is that a try block is a context for quit, so if you have a quit command in a loop, then introduce a try-catch block, the quit may no longer do what you expect:

for i=1:1:10 {
    if i>4 {
        quit
    }
}

for i=1:1:10 {
    try {
        if i>4 {
            quit  // oops
        }
    } catch {}
}

Otherwise, I find try-catch easier to visualize than $ztrap. Unfortunately, there is no finally block.

Looking through some of my old code, I see a lot of $ztrap for restoring the previous namespace on error. A lot of those can now be replaced with new $namespace.

1: Yes 😉
2: See other comment on Quit
3: yes 😉
You should never 'modernize' for the sake of modernizing (refactoring is something else)
ZTrap is not old-fashioned, it's a mechanism other programming languages just don't have.
It is out-of-the-way, is doesn't introduce another stack level and it doesn't need extra indentation, it's just some code that you hope will never be executed, it isn't part of the main logic.
Try-Catch can be very useful for indeed a 'Try' for something you can't be sure how it will behave, such as
{}.%FromJSON(SomeJSON)

I am a huge fan of try/catch. The try is virtually cost-free with overhead only encountered when an exception is caught. I do agree with Jon Willeke - when I am in older code I normally do not refactor $ZTRAP unless the changes I have to make are more than a simple edit. I also use RETURN when exiting a function/method instead of QUIT.

It is possible to simluate a finally but it isn't as nice as having a real finally block would be.