9/23/2016
TclErrorHandling
TclErrorHandling
Advertisements
PreviousPage
NextPage
ErrorhandlinginTclisprovidedwiththehelpoferrorandcatchcommands.Thesyntaxfor
eachofthesecommandsisshownbelow.
Errorsyntax
errormessageinfocode
Intheaboveerrorcommandsyntax,messageistheerrormessage,infoissetintheglobal
variableerrorInfoandcodeissetintheglobalvariableerrorCode.
CatchSyntax
catchscriptresultVarName
In the above catch command syntax, script is the code to be executed, resultVarNameis
variablethatholdstheerrorortheresult.Thecatchcommandreturns0ifthereisnoerror,
and1ifthereisanerror.
Anexampleforsimpleerrorhandlingisshownbelow
https://www.tutorialspoint.com/tcltk/tcl_error_handling.htm
1/3
9/23/2016
TclErrorHandling
#!/usr/bin/tclsh
procDiv{ab}{
if{$b==0}{
error"Errorgeneratedbyerror""InfoStringforerror"401
}else{
return[expr$a/$b]
}
}
if{[catch{puts"Result=[Div100]"}errmsg]}{
puts"ErrorMsg:$errmsg"
puts"ErrorCode:$errorCode"
puts"ErrorInfo:\n$errorInfo\n"
}
if{[catch{puts"Result=[Div102]"}errmsg]}{
puts"ErrorMsg:$errmsg"
puts"ErrorCode:$errorCode"
puts"ErrorInfo:\n$errorInfo\n"
}
Whentheabovecodeisexecuted,itproducesthefollowingresult
ErrorMsg:Errorgeneratedbyerror
ErrorCode:401
ErrorInfo:
InfoStringforerror
(procedure"Div"line1)
invokedfromwithin
"Div100"
Result=5
As you can see in the above example, we can create our own custom error messages.
Similarly,itispossibletocatchtheerrorgeneratedbyTcl.Anexampleisshownbelow
#!/usr/bin/tclsh
catch{setfile[openmyNonexistingfile.txt]}result
puts"ErrorMsg:$result"
puts"ErrorCode:$errorCode"
puts"ErrorInfo:\n$errorInfo\n"
Whentheabovecodeisexecuted,itproducesthefollowingresult
ErrorMsg:couldn'topen"myNonexistingfile.txt":nosuchfileordirectory
ErrorCode:POSIXENOENT{nosuchfileordirectory}
ErrorInfo:
couldn'topen"myNonexistingfile.txt":nosuchfileordirectory
whileexecuting
"openmyNonexistingfile.txt"
https://www.tutorialspoint.com/tcltk/tcl_error_handling.htm
2/3
9/23/2016
TclErrorHandling
PreviousPage
NextPage
Advertisements
Write for us
FAQ's
Helping
Contact
Copyright 2016. All Rights Reserved.
Enter email for newsletter
https://www.tutorialspoint.com/tcltk/tcl_error_handling.htm
go
3/3