try:else: w/o except: - why not?

Peter Hansen peter at engcorp.com
Tue Apr 1 03:03:43 CEST 2003


Manus Hand wrote:
> 
> I know that if you want to use else: on a try: block, you need to
> specify one or more except: clauses.  I guess my question is why
> this should need to be.
> 
> Personally, I have cases where it would be nice to do this:
> 
> try:
>     # some code that may except
> else:
>     # but if it didn't except, I want to do this
> 
> Instead of writing the code that way, I need to write this:
> 
> try:
>     # some code that may except
> except:
>     # and if it does, then, okay, just ignore it
>     pass
> else:
>     # but if it didn't except, I want to do this

No, actually to get the behaviour you presumably want, you would
have to write this:

try:
    # stuff
except:
    raise  # pass would just swallow the exception!
else:
    # do this when no exception

What you wrote in the first place is exactly the same as this:

# some code that may except
# but if it didn't except, I want to do this

In other words, the "try" in your first block is useless....

-Peter




More information about the Python-list mailing list