try:else: w/o except: - why not?
John Roth
johnroth at ameritech.net
Mon Mar 31 20:23:32 EST 2003
"Peter Hansen" <peter at engcorp.com> wrote in message
news:3E88E56F.5CB4EB92 at engcorp.com...
> 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....
Not quite. Consider a test that's supposed to throw an exception
in a testing harness like unittest or xUnit. If it throws an exception,
the test passes, and if it doesn't, I want to put out a diagnostic
message.
Now, that's a bit too simplistic for my use - I'd like to know that
it threw the *correct* exception. But that's a use case for the
facility he's asking for.
John Roth
>
> -Peter
More information about the Python-list
mailing list