Subject: Re: Extending "catch" syntax? - DN [1]


orb@cs.utexas.edu (Norman Richards) - 17 Apr 1999 - comp.lang.tcl

 On Sat, 17 Apr 1999 23:21:14 +0200, Jean-Claude Wippler <jcw@equi4.com> wrote:
 > Often, I find myself writing the following code:
 >
 >     if {[catch {blah} errmsg]} {
 >         ... do something with $errmsg ...
 >     }
 >
 > Could the catch syntax be extended as follows, with the same semantics?
 >
 >     catch {blah} errmsg {
 >         ... do something with $errmsg ...
 >     }

   Yes, the catch syntax is terrible.  Actually, I find myself mostly doing:

 if {[catch {cmd} err]} {
     foo
 } else {
     bar
 }

   What I did to make things nicer was to write a try function which works
 something like this:

 try result {
    # do the command sequence
 } error {
    # do something to handle the error condition
 } success {
    # do something to handle the success condition
 }

   I also added in an always clause for code that should always execute
 regardless of success or failure.  But I have not yet decided whether
 it is really useful or if it is just fluff.  In any case, here is
 what I wrote.  If anyone has suggestions on how to make it better,
 please let me know.

 proc try {var cmd args} {
     upvar $var resvar

     set errcode [catch {uplevel 1 $cmd} resvar]
     foreach {tag code} $args {
         switch -- $tag {
             error {
                 if {$errcode!=0} {
                     uplevel 1 $code
                 }
             }
             success {
                 if {$errcode==0}  {
                     uplevel 1 $code
                 }
             }
             always {
                 uplevel 1 $code
             }
             default {
                 error "unknown try tag $tag, should be error, success or always"
             }
         }
     }
 }

 ___________________________________________________________________________
 orb@cs.utexas.edu                                           soli deo gloria

Last modified
1999-09-27

(195.108.246.50)

Note: you are looking at
the snapshot of an old wiki
- much of this information
is likely to be very outdated