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

Cameron Laird claird at lairds.com
Mon Mar 31 20:26:51 EST 2003


In article <v8hq9dnt25ke89 at news.supernews.com>,
John Roth <johnroth at ameritech.net> wrote:
>
>"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.
			.
			.
			.
I get *that* point--and thanks for articulating it.  What I
don't understand is why one would prefer
  try:
      f1()
  else:
      f2()
over
  try:
      f1()
      f2()
APART from the fact that the f2() in the second coding is
"protected".  Is that the implicit intention of Mr. Hand that
everyone else recognized?
-- 

Cameron Laird <Cameron at Lairds.com>
Business:  http://www.Phaseit.net
Personal:  http://phaseit.net/claird/home.html




More information about the Python-list mailing list