
- Tcl Tutorial
- Tcl - Home
- Tcl - Overview
- Tcl - Environment Setup
- Tcl - Special Variables
- Tcl - Basic Syntax
- Tcl - Commands
- Tcl - Data Types
- Tcl - Variables
- Tcl - Operators
- Tcl - Decisions
- Tcl - Loops
- Tcl - Arrays
- Tcl - Strings
- Tcl - Lists
- Tcl - Dictionary
- Tcl - Procedures
- Tcl - Packages
- Tcl - Namespaces
- Tcl - File I/O
- Tcl - Error Handling
- Tcl - Built-in Functions
- Tcl - Regular Expressions
- Tk Tutorial
- Tk - Overview
- Tk - Environment
- Tk - Special Variables
- Tk - Widgets Overview
- Tk - Basic Widgets
- Tk - Layout Widgets
- Tk - Selection Widgets
- Tk - Canvas Widgets
- Tk - Mega Widgets
- Tk - Fonts
- Tk - Images
- Tk - Events
- Tk - Windows Manager
- Tk - Geometry Manager
- Tcl/Tk Useful Resources
- Tcl/Tk - Quick Guide
- Tcl/Tk - Useful Resources
- Tcl/Tk - Discussion
Tcl - Error Handling
Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below.
Error syntax
error message info code
In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode.
Catch Syntax
catch script resultVarName
In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error.
An example for simple error handling is shown below −
#!/usr/bin/tclsh proc Div {a b} { if {$b == 0} { error "Error generated by error" "Info String for error" 401 } else { return [expr $a/$b] } } if {[catch {puts "Result = [Div 10 0]"} errmsg]} { puts "ErrorMsg: $errmsg" puts "ErrorCode: $errorCode" puts "ErrorInfo:\n$errorInfo\n" } if {[catch {puts "Result = [Div 10 2]"} errmsg]} { puts "ErrorMsg: $errmsg" puts "ErrorCode: $errorCode" puts "ErrorInfo:\n$errorInfo\n" }
When the above code is executed, it produces the following result −
ErrorMsg: Error generated by error ErrorCode: 401 ErrorInfo: Info String for error (procedure "Div" line 1) invoked from within "Div 10 0" Result = 5
As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below −
#!/usr/bin/tclsh catch {set file [open myNonexistingfile.txt]} result puts "ErrorMsg: $result" puts "ErrorCode: $errorCode" puts "ErrorInfo:\n$errorInfo\n"
When the above code is executed, it produces the following result −
ErrorMsg: couldn't open "myNonexistingfile.txt": no such file or directory ErrorCode: POSIX ENOENT {no such file or directory} ErrorInfo: couldn't open "myNonexistingfile.txt": no such file or directory while executing "open myNonexistingfile.txt"