user31208
user31208

Reputation: 1480

In Tcl, what is the equivalent of "set -e" in bash?

Is there a convenient way to specify in a Tcl script to immediately exit in case any error happens? Anything similar to set -e in bash?

EDIT I'm using a software that implements Tcl as its scripting language. If for example I run the package parseSomeFile fname, if the file fname does't exist, it reports it but the script execution continues. Is there a way that I stop the script there?

Upvotes: 0

Views: 293

Answers (2)

Hai Vu
Hai Vu

Reputation: 40733

In Tcl, if you run into an error, the script will exit immediately unless you catch it. That means you don't need to specify the like of set -e.

Update

Ideally, parseSomeFile should have return an error, but looks like it does not. If you have control over it, fix it to return an error:

proc parseSomeFile {filename} {
    if {![file exists $filename]} {
        return -code error "ERROR: $filename does not exists"
    }
    # Do the parsing
    return 1
}

# Demo 1: parse existing file
parseSomeFile foo

# Demo 2: parse non-existing file
parseSomeFile bar

The second option is to check for file existence before calling parseSomeFile.

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137637

It's usually not needed; a command fails by throwing an error which makes the script exit with an informative message if not caught (well, depending on the host program: that's tclsh's behavior). Still, if you need to really exit immediately, you can hurry things along by putting a trace on the global variable that collects error traces:

trace add variable ::errorInfo write {puts stderr $::errorInfo;exit 1;list}

(The list at the end just traps the trace arguments so that they get ignored.)

Doing this is not recommended. Existing Tcl code, including all packages you might be using, assumes that it can catch errors and do something to handle them.

Upvotes: 1

Related Questions