[Python-ideas] try-else without except or finally

Guido van Rossum guido at python.org
Fri Nov 11 04:50:45 CET 2011


On Thu, Nov 10, 2011 at 7:41 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Fri, Nov 11, 2011 at 9:43 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> However, Terry's explanation of Dennis' observation that any hypothetical
>> try...else...finally block can be re-written as try...finally satisfies me.
>> That's a good enough reason to keep the status quo.
>>
>> Downgrading my vote from +1 to +0.
>
> A full -1 from me, for the reason already given: it's completely
> redundant. The "else:" clause on try statements exists specifically to
> cover the following situation:
>
> 1. You have code in a try block that may trigger associated exception handlers
> 2. One or more of those exception handlers may suppress the exception,
> allowing execution to resume after the try statement
> 3. You have some code that you want to run *only* if the try block
> doesn't throw an exception (i.e. if an exception is thrown and
> suppressed, you don't want to run this section of the code)

4. You don't want exceptions is the else-block to be handled by any of
the handlers. (Otherwise you could just put the else-block's code at
the end of the try-block.)

> If none of your exception handlers can suppress the exception and
> there's either no "finally:" close or it's OK if the additional code
> runs after the cleanup code, then "else:" is not really needed - you
> can just write the additional code after the whole try statement.
>
> If there are no exception handlers at all, then either don't use a try
> statement at all, or use a simple try-finally statement if you need
> some guaranteed cleanup.

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list