[Tutor] anecdote in the workplace about try,except clause

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 16 Aug 2001 19:43:08 -0700 (PDT)


On Thu, 16 Aug 2001, Sean 'Shaleh' Perry wrote:

> A coworker who is a long time perl'er is learning python and asking me
> questions now and then.  Today he was writing a file parser and did
> the following:
> 
> for line in file:
>     try:
>         data, garbage = string.split(line, ':')
>     except ValueError:
>         pass
> 
>     print 'Data: %s' % data
> 
> 
> His rationale was that some lines lack the ':' so he would just let the
> exception hide the 'annoying' python exception assuming that data would be
> assigned the whole line in that case.
> 
> What he failed to realize is that when the except clause is triggered
> items in the try clause go out of scope.  So data would not exist.


Or, at least, the very last data will be the only thing printed out.  
Your friend probably meant to write it like this:

###
for line in file:
    try:
        data, garbage = string.split(line, ':')
        print 'Data: %s' % data
    except ValueError: pass
###

Feel free to direct your coworker to us; we'd be happy to meet them!  
*grin*