Description
Executes script lines and traps exceptions.
Exceptions generated during execution of a script are errors that cause the current script to be aborted, forcing the process itself to be terminated. Some of the examples of such an error are those generated depending on run-time conditions such as an error on file open (open command), abnormal termination of the process being executed (i.e. completion code is other than 0 with exec command), in addition to a syntax error in the current script being executed, or variable substitutions attempted on variables with no associated values.
The catch command is used to prevent script process from being terminated by running its own recovery process when such exceptions occur.
Synopsis
catch {script} [varname]
Options
Script command to run. Two or more commands can be written by separating them by line breaks or semicolons.
The name of a variable that stores an error text giving the cause of an exception, if occurred. If omitted, the error text will not be stored.
Return Values
No exceptions have occurred.
Exceptions have occurred.
In this case, the following value is stored as detailed information in the global variable errorCdoe:
When the completion code of the command executed by the script command "exec" is other than 0
CHILDSTATUS pid exitcode
[Windows]
Numeric characters entered in this field do not have any meaning
[UNIX]
The process ID of the command executed
The completion code of the command executed
When the command executed by the script command "exec" is forcibly terminated by a signal
CHILDKILLED pid sigName msg
[Windows]
Numeric characters entered in this field do not have any meaning.
[UNIX]
The process ID of the command executed
The name of the signal sent to the command executed
Detailed message
When the command executed by the script command "exec" is suspended by a signal
CHILDSUSP pid sigName msg
[Windows]
Numeric characters entered in this field do not have any meaning.
[UNIX]
The process ID of the command executed
The name of the signal sent to the process
Detailed message
When an arithmetic error occurred in the script command "expr"
ARITH errName msg
Error contents
Detailed message
When an error occurred in the system call
POSIX errName msg
Error contents
Detailed message
When there is no information to be returned with the error other than the relevant message
NONE
Example
The following example opens a file for reading and if fails, enables reading from the standard input.
if {[catch { set file [open data.txt r] }]} { set file "stdin" } gets $file buf if {$file != "stdin"} { close $file }