1catch(n) Tcl Built-In Commands catch(n)
2
3
4
5______________________________________________________________________________
6
8 catch - Evaluate script and trap exceptional returns
9
11 catch script ?varName?
12_________________________________________________________________
13
14
16 The catch command may be used to prevent errors from aborting command
17 interpretation. The catch command calls the Tcl interpreter recur‐
18 sively to execute script, and always returns without raising an error,
19 regardless of any errors that might occur while executing script.
20
21 If script raises an error, catch will return a non-zero integer value
22 corresponding to the exceptional return code returned by evaluation of
23 script. Tcl defines the normal return code from script evaluation to
24 be zero (0), or TCL_OK. Tcl also defines four exceptional return
25 codes: 1 (TCL_ERROR), 2 (TCL_RETURN), 3 (TCL_BREAK), and 4 (TCL_CON‐
26 TINUE). Errors during evaluation of a script are indicated by a return
27 code of TCL_ERROR. The other exceptional return codes are returned by
28 the return, break, and continue commands and in other special situa‐
29 tions as documented. Tcl packages can define new commands that return
30 other integer values as return codes as well, and scripts that make use
31 of the return -code command can also have return codes other than the
32 five defined by Tcl.
33
34 If the varName argument is given, then the variable it names is set to
35 the result of the script evaluation. When the return code from the
36 script is 1 (TCL_ERROR), the value stored in varName is an error mes‐
37 sage. When the return code from the script is 0 (TCL_OK), the value
38 stored in resultVarName is the value returned from script.
39
40 If script does not raise an error, catch will return 0 (TCL_OK) and set
41 the variable to the value returned from script.
42
43 Note that catch catches all exceptions, including those generated by
44 break and continue as well as errors. The only errors that are not
45 caught are syntax errors found when the script is compiled. This is
46 because the catch command only catches errors during runtime. When the
47 catch statement is compiled, the script is compiled as well and any
48 syntax errors will generate a Tcl error.
49
50
52 The catch command may be used in an if to branch based on the success
53 of a script.
54 if { [catch {open $someFile w} fid] } {
55 puts stderr "Could not open $someFile for writing\n$fid"
56 exit 1
57 }
58
59 The catch command will not catch compiled syntax errors. The first
60 time proc foo is called, the body will be compiled and a Tcl error will
61 be generated.
62 proc foo {} {
63 catch {expr {1 +- }}
64 }
65
66
68 break(n), continue(n), error(n), return(n), tclvars(n)
69
70
72 catch, error
73
74
75
76Tcl 8.0 catch(n)