Reputation: 2868
In my Tcl/Tk script, there is one step to remove some txt file. I use:
exec rm file1.txt
But if the file dose not exist, then error message will come up which will block the script usage. What I want to do is remove the file if it exist, and if it does not exist, to skip the error. Is there a good way of doing this?
Ok, I find the answer: file exists filename
works well for this case.
Upvotes: 0
Views: 3170
Reputation: 13252
How to avoid having an error stop your program.
The "0th" solution is to use commands that don't raise errors. such as glob -nocomplain
instead of just glob
, or in this case file delete file1.txt
as suggested by timrau.
In some cases it's impossible to prevent errors from being raised. In those cases you can choose from several strategies. Assume you need to call mycmd
, and it might raise errors.
# Tcl 8.6
try mycmd on error {} {}
# Tcl 8.4 or later
catch mycmd
This invocation quietly intercepts the error and lets your program continue. This is perfectly acceptable if the error isn't important, e.g. when you attempt to discard a variable that might not exist (catch {unset myvar}
).
You might want to take some action when an error is raised, such as reporting it to yourself (as an error message on stderr
or in a message box, or in a log of some kind) or by dealing with the error somehow.
try mycmd on error msg {puts stderr "There was a problem: $msg"}
if {[catch mycmd msg]} {
puts stderr "There was a problem: $msg"
}
You might want to take some action only if there was no error:
try {
mycmd
} on ok res {
puts "mycmd returned $res"
} on error msg {
puts stderr "There was a problem: $msg"
}
if {[catch mycmd res]} {
puts stderr "There was a problem: $res"
} else {
puts "mycmd returned $res"
}
For instance, this invocation returns the contents of a file, or the empty string if the file doesn't exist. It makes sure that the channel is closed and the variable holding the channel identifier are destroyed in either case:
set txt [try {
open $filename
} on ok f {
chan read $f
} on error msg {
puts stderr $msg
} finally {
catch {chan close $f}
catch {unset f}
}]
Documentation: catch, chan, file, glob, if, open, puts, set, try
Upvotes: 0
Reputation: 23058
You could use
file delete file1.txt
where trying to delete a non-existent file is not considered an error.
Upvotes: 5