Error Handling
If an error occurs while a thread is executing its creation script (provided by thread::create), the thread dies. In contrast, if an error occurs while processing a message script (provided by thread::send), the default behavior is for the thread to stop execution of the message script, but to return to its event loop and continue running. To cause a thread to die when it encounters an uncaught error, use the thread::configure command to set the thread's -unwindonerror option to true:
thread::configure $t -unwindonerror 1
Error handling is determined by the thread creating the thread or sending the message. If an error occurs in a script sent by a synchronous thread::send, then the error condition is "reflected" to the sending thread, as described in "Synchronous Message Sending" on page 328. If an error occurs during thread creation or an asynchronous thread::send, the default behavior is for Tcl to send a stack trace to the standard error channel. Alternatively, you can specify the name of your own custom error handling procedure with thread::errorproc. Tcl automatically calls your procedure whenever an "asynchronous" error occurs, passing it two arguments: the ID of the thread generating the error, and the stack trace. (This is similar to defining your own bgerror procedure, as described in "The bgerror Command" on page 202.) For example, the following code logs all uncaught errors to the file errors.txt:
Example 21-8 Creating a custom thread error handler
set errorFile [open errors.txt a]
proc logError {id error} {
global errorFile
puts $errorFile "Error in thread $id"
puts $errorFile $error
puts $errorFile ""
}
thread::errorproc logError
 |