Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 760 – No More Bare Excepts

PEP 760 – No More Bare Excepts

Author:
Pablo Galindo Salgado <pablogsal at python.org>, Brett Cannon <brett at python.org>
Status:
Withdrawn
Type:
Standards Track
Created:
02-Oct-2024
Python-Version:
3.14
Post-History:
09-Oct-2024

Table of Contents

Abstract

This PEP proposes disallowing bareexcept: clauses in Python’sexception-handling syntax. Currently, Python allows catching all exceptionswith a bareexcept: clause, which can lead to overly broad exceptionhandling and mask important errors. This PEP suggests requiring explicitexception types in all except clauses, promoting more precise and intentionalerror handling.

Motivation

The current syntax allows for catching all exceptions with a bareexcept: clause:

try:risky_operation()except:handle_any_error()

While this syntax can be convenient for a “catch all” handler, it often leadsto poor coding practices:

  1. It can mask important errors that should be propagated.
  2. It makes debugging more difficult by catching and potentially hidingunexpected exceptions.
  3. It goes against the Python principle of explicit over implicit.

Various linters[1][2][3] and style guides (includingPEP 8)[4][5][6][7] discourage bareexcept clauses.

By requiring explicit exception types, we can encourage more thoughtful andprecise error handling:

try:risky_operation()exceptExceptionase:handle_expected_error(e)

Another view of this problem is that bare except handlers are ambiguousregarding the intended handling of terminating exceptions, as the intentioncould have been either:

  • Only catch non-terminating exceptions (exceptException:). If this was theintention, using a bareexcept: is an outright bug, since that isn’t what itmeans.
  • Catch all exceptions, including terminating ones (exceptBaseException:).using bareexcept: here it is at least correct, but readers need to checkto be sure it isn’t an instance of the first case.

Since both possible intentions have available unambiguous spellings, theambiguous form is redundant and that’s why we propose to disallow it.

Rationale

The decision to disallow bare except clauses is based on the followingconsiderations:

  1. Requiring specific exception types makes the programmer’s intentions clearand encourages thinking about what exceptions might occur.
  2. Catching only specific exceptions makes identifying and debugging unexpectederrors easier.
  3. Preventing overly broad exception handling reduces the risk of silentlyignoring critical errors.
  4. Many style guides and linters already discourage the use of bare exceptclauses.

Specification

The syntax for the except clause will be modified to require an exception type.The grammar will be updated to remove the possibility of adding an emptyexpression in except clauses.

This change disallows the bareexcept: syntax. All except clauses mustspecify at least one exception type:

try:...exceptValueError:...except(TypeError,RuntimeError):...exceptException:...# Still allowed, but catches all exceptions explicitly

The semantics of exception handling remain unchanged, except that it will nolonger be possible to catch all exceptions without explicitly specifyingBaseException or a similarly broad exception type.

Backwards Compatibility

This change is not backwards compatible. Existing code that uses bareexcept:clauses will need to be modified. To ease the transition:

  1. A deprecation warning will be issued for bare except clauses in Python 3.14.
  2. The syntax will be fully disallowed in Python 3.17.
  3. Afrom__future__importstrict_excepts will be provided to invalidate bareexcept handlers in earlier versions of Python.

A tool will be provided to automatically update code to replace bareexcept:withexceptBaseException:.

Security Implications

This change has no security implications.

How to Teach This

For new Python users, exception handling should be taught with explicitexception types from the start:

try:result=risky_operation()exceptValueError:handle_value_error()exceptTypeError:handle_type_error()exceptExceptionase:handle_unexpected_error(e)

For experienced users, the change can be introduced as a best practice that isnow enforced by the language. The following points should be emphasized:

  1. Always catch specific exceptions when possible.
  2. UseexceptException: as a last resort for truly unexpected errors.
  3. Never silence exceptions without careful consideration.

Documentation should guide common exception hierarchies and how to chooseappropriate exception types to catch.

Rejected ideas

  • There are genuine cases where the use of bareexcept: handlers are correct. oneof the examples that have been raised from Mailman[8] involves handling transactionsin the face of any exception:
    @contextmanagerdeftransaction():"""Context manager for ensuring the transaction is complete."""try:yieldexcept:config.db.abort()raiseelse:config.db.commit()

    This code guarantees that no matter what exception occurs, any opentransaction will be aborted, while in the successful condition, thetransaction will be committed.

    We do believe that although there are cases such like this one wherebareexcept: handlers are correct, it would be better to actuallybe explicit and useexceptBaseException: for the reasons indicatedin the “Motivation” section.

Copyright

This document is placed in the public domain or under theCC0-1.0-Universal license, whichever is more permissive.

[1]
https://pylint.pycqa.org/en/latest/user_guide/messages/warning/bare-except.html
[2]
https://www.flake8rules.com/rules/E722.html
[3]
https://docs.astral.sh/ruff/rules/bare-except/
[4]
https://google.github.io/styleguide/pyguide.html#24-exceptions
[5]
https://chromium.googlesource.com/chromiumos/platform/factory/+/HEAD/CODING_STYLE.md#Avoid-bare_except
[6]
https://4.docs.plone.org/develop/plone-coredev/style.html#concrete-rules
[7]
https://docs.openedx.org/en/latest/developers/references/developer_guide/style_guides/python-guidelines.html
[8]
https://gitlab.com/mailman/mailman/-/blob/master/src/mailman/database/transaction.py#L27

Source:https://github.com/python/peps/blob/main/peps/pep-0760.rst

Last modified:2025-11-07 04:32:09 GMT


[8]ページ先頭

©2009-2026 Movatter.jp