Following system colour scheme Selected dark colour scheme Selected light colour scheme

Python Enhancement Proposals

PEP 341 – Unifying try-except and try-finally

Author:
Georg Brandl <georg at python.org>
Status:
Final
Type:
Standards Track
Created:
04-May-2005
Python-Version:
2.5
Post-History:


Table of Contents

Abstract

This PEP proposes a change in the syntax and semantics of try statements to allow combined try-except-finally blocks. This means in short that it would be valid to write:

try:
    <do something>
except Exception:
    <handle the error>
finally:
    <cleanup>

Rationale/Proposal

There are many use cases for the try-except statement and for the try-finally statement per se; however, often one needs to catch exceptions and execute some cleanup code afterwards. It is slightly annoying and not very intelligible that one has to write:

f = None
try:
    try:
        f = open(filename)
        text = f.read()
    except IOError:
        print 'An error occurred'
finally:
    if f:
        f.close()

So it is proposed that a construction like this:

try:
    <suite 1>
except Ex1:
    <suite 2>
<more except: clauses>
else:
    <suite 3>
finally:
    <suite 4>

be exactly the same as the legacy:

try:
    try:
        <suite 1>
    except Ex1:
        <suite 2>
    <more except: clauses>
    else:
        <suite 3>
finally:
    <suite 4>

This is backwards compatible, and every try statement that is legal today would continue to work.

Changes to the grammar

The grammar for the try statement, which is currently:

try_stmt: ('try' ':' suite (except_clause ':' suite)+
        ['else' ':' suite] | 'try' ':' suite 'finally' ':' suite)

would have to become:

try_stmt: 'try' ':' suite
        (
            (except_clause ':' suite)+
            ['else' ':' suite]
            ['finally' ':' suite]
        |
            'finally' ':' suite
        )

Implementation

As the PEP author currently does not have sufficient knowledge of the CPython implementation, he is unfortunately not able to deliver one. Thomas Lee has submitted a patch [2].

However, according to Guido, it should be a piece of cake to implement [1] – at least for a core hacker.

This patch was committed 17 December 2005, SVN revision 41740 [3].

References


Source: https://github.com/python/peps/blob/main/pep-0341.txt

Last modified: 2022-08-24 22:40:18 GMT