try/except/else flexibility...

Bertrand Geston bergeston at yahoo.fr
Fri Apr 12 06:38:49 EDT 2002


"Magnus Lie Hetland" <mlh at vier.idi.ntnu.no> wrote in message
news:slrnabcon3.g5r.mlh at vier.idi.ntnu.no...
> Just a thought: Given the prevalence of try/except/else in the "don't
> look before you leap" way of doing things, could it be useful to make
> the statement more flexible? For instance, instead of writing
>
>   try: foo + ''
>   except: pass
>   else: bar()
>
> (assuming I'm sloppy enough not to specify TypeError on the second
> line) one could simply write:
>
>   try: foo + ''
>   else: bar()
>
> and if I want something done only if it causes no exceptions, for
> instance pop off an element of a list unless it is empty, I could just
> do:
>
>   try: somelist.pop()
>
Just to remember you: ;-)))
>>> Explicit is better than implicit.
>>> Special cases aren't special enough to break the rules.
and if you want something more explicit:
>>> Errors should never pass silently.
>>> Unless explicitly silenced.
And then you could always use something like that (and let the console
remind you how you like to take risks)
>>> def tryAndForget(f, *args, **kw):
...  try:
...   return apply(f, args, kw)
...  except :
...   print('I like to live dangerously')


> Is this heresy? I see the harm in not specifying exactly which
> exceptions you're expecting, of course -- are there other arguments
> against this? (I'm sure that might be argument enough... Oh, well...)

More seriously, I think that:
try:
    ...
except:
    pass
means something like 'if there is something wrong that I didn't foresee,
please, please don't tell me' which remind me the joke of the guy falling
from a building and saying during the drop 'until now, it's all right, ...
until now, it's all right, ... until now, it's all right ...' (sorry for my
english, it's implemented as you like: every exception is silently absorbed
;-)

The perspective is completely different if you log evething that you didn't
foresee. A kinda tryAndLog function makes sense in some development phases
IMHO.

Have a nice WE

B.

>
> --
> Magnus Lie Hetland                                  The Anygui Project
> http://hetland.org                                  http://anygui.org






More information about the Python-list mailing list