Harald Oehlmann <
wort...@yahoo.de> wrote:
> Rich,
> thank you for the discussion. A part is added on the wiki page:
>
>
https://wiki.tcl-lang.org/page/try
>
> Feel free to modify.
>
> A native speaker (e.g. not me) may judge, if the man page is clear
> enough. Nevertheless, I would appreciate an example like on the wiki now
> and some clarifying words.
You say this in the Wiki:
I only see a use-case for this case. Otherwise, you may just write
the finally part after the try command and all is the same.
I see the 'use case' for finally as being able to place all cleanup
code in one spot.
I.e., no 'try':
proc x {...} {
# do something that allocates something that we have to manually
# deallocate (opening files, creating a struct::matrix or
# struct::graph, etc.)
set r [catch {perform something that might error} a b]
if {$r} {
# caught an error
# we have to cleanup, here, all the stuff we allocated at entry to
# the proc
return -code error
}
# normal no error code path
# ...
# ...
# ...
# ...
# done - now we have to cleanup everything we allocated at the start
# of the proc
return
}
In the above, as the proc evolves, we might allocate more (or less)
stuff at the start of the proc, and we have (above) two places in the
proc to edit for "cleanup". Two separate places to edit, containing
the same code, means they might get out of sync with each other. And,
because they are error handling paths, an out of sync error path will
go unnoticed until the error happens to trigger one day.
With 'finally', the proc can be refactored to be:
proc x {...} {
# allocate stuff
try {
# ...
} trap {} {} {
# ...
} trap {} {} {
# ...
} finally {
# cleanup the allocated stuff
}
}
Now, no matter how many different 'trap' handlers you use, there's only
one cleanup, and it always executes, so cleanup always occurs. Less
code duplication, less chance of code getting out of sync.