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

Nick Coghlan ncoghlan at gmail.com
Fri Nov 11 04:41:29 CET 2011


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)

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.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list