|
| 1 | +PEP: 760 |
| 2 | +Title: No More Bare Excepts |
| 3 | +Author: Pablo Galindo < [email protected]>, Brett Cannon < [email protected]> |
| 4 | +Status: Draft |
| 5 | +Type: Standards Track |
| 6 | +Created: 02-Oct-2024 |
| 7 | +Python-Version: 3.14 |
| 8 | + |
| 9 | + |
| 10 | +Abstract |
| 11 | +======== |
| 12 | + |
| 13 | +This PEP proposes disallowing bare ``except:`` clauses in Python's |
| 14 | +exception-handling syntax. Currently, Python allows catching all exceptions |
| 15 | +with a bare ``except:`` clause, which can lead to overly broad exception |
| 16 | +handling and mask important errors. This PEP suggests requiring explicit |
| 17 | +exception types in all except clauses, promoting more precise and intentional |
| 18 | +error handling. |
| 19 | + |
| 20 | +Motivation |
| 21 | +========== |
| 22 | + |
| 23 | +The current syntax allows for catching all exceptions with a bare ``except:`` clause: |
| 24 | + |
| 25 | +.. code-block:: python |
| 26 | +
|
| 27 | + try: |
| 28 | + risky_operation() |
| 29 | + except: |
| 30 | + handle_any_error() |
| 31 | +
|
| 32 | +While this syntax can be convenient for a "catch all" handler, it often leads |
| 33 | +to poor coding practices: |
| 34 | + |
| 35 | +1. It can mask important errors that should be propagated. |
| 36 | +2. It makes debugging more difficult by catching and potentially hiding |
| 37 | + unexpected exceptions. |
| 38 | +3. It goes against the Python principle of explicit over implicit. |
| 39 | + |
| 40 | +Various linters [1]_ [2]_ [3]_ and style guides (including :pep:`8`) [4]_ [5]_ |
| 41 | +[6]_ [7]_ discourage bare ``except`` clauses. |
| 42 | + |
| 43 | +By requiring explicit exception types, we can encourage more thoughtful and |
| 44 | +precise error handling: |
| 45 | + |
| 46 | +.. code-block:: python |
| 47 | +
|
| 48 | + try: |
| 49 | + risky_operation() |
| 50 | + except Exception as e: |
| 51 | + handle_expected_error(e) |
| 52 | +
|
| 53 | +Another view of this problem is that bare except handlers are ambiguous |
| 54 | +regarding the intended handling of terminating exceptions, as the intention |
| 55 | +could have been either: |
| 56 | + |
| 57 | +* Only catch non-terminating exceptions (``except Exception:``). If this was the |
| 58 | + intention, using a bare ``except:`` is an outright bug, since that isn't what it |
| 59 | + means. |
| 60 | +* Catch all exceptions, including terminating ones (``except BaseException:``). |
| 61 | + using bare ``except:`` here it is at least correct, but readers need to check |
| 62 | + to be sure it isn't an instance of the first case. |
| 63 | + |
| 64 | +Since both possible intentions have available unambiguous spellings, the |
| 65 | +ambiguous form is redundant and that's why we propose to disallow it. |
| 66 | + |
| 67 | +Rationale |
| 68 | +========= |
| 69 | + |
| 70 | +The decision to disallow bare except clauses is based on the following |
| 71 | +considerations: |
| 72 | + |
| 73 | +1. Requiring specific exception types makes the programmer's intentions clear |
| 74 | + and encourages thinking about what exceptions might occur. |
| 75 | + |
| 76 | +2. Catching only specific exceptions makes identifying and debugging unexpected |
| 77 | + errors easier. |
| 78 | + |
| 79 | +3. Preventing overly broad exception handling reduces the risk of silently |
| 80 | + ignoring critical errors. |
| 81 | + |
| 82 | +4. Many style guides and linters already discourage the use of bare except |
| 83 | + clauses. |
| 84 | + |
| 85 | + |
| 86 | +Specification |
| 87 | +============= |
| 88 | + |
| 89 | +The syntax for the except clause will be modified to require an exception type. |
| 90 | +The grammar will be updated to remove the possibility of adding an empty |
| 91 | +expression in except clauses. |
| 92 | + |
| 93 | +This change disallows the bare ``except:`` syntax. All except clauses must |
| 94 | +specify at least one exception type: |
| 95 | + |
| 96 | +.. code-block:: python |
| 97 | +
|
| 98 | + try: |
| 99 | + ... |
| 100 | + except ValueError: |
| 101 | + ... |
| 102 | + except (TypeError, RuntimeError): |
| 103 | + ... |
| 104 | + except Exception: |
| 105 | + ... # Still allowed, but catches all exceptions explicitly |
| 106 | +
|
| 107 | +The semantics of exception handling remain unchanged, except that it will no |
| 108 | +longer be possible to catch all exceptions without explicitly specifying |
| 109 | +``BaseException`` or a similarly broad exception type. |
| 110 | + |
| 111 | + |
| 112 | +Backwards Compatibility |
| 113 | +======================= |
| 114 | + |
| 115 | +This change is not backwards compatible. Existing code that uses bare ``except:`` |
| 116 | +clauses will need to be modified. To ease the transition: |
| 117 | + |
| 118 | +1. A deprecation warning will be issued for bare except clauses in Python 3.14. |
| 119 | +2. The syntax will be fully disallowed in Python 3.17. |
| 120 | +3. A ``from __future__ import strict_excepts`` will be provided to invalidate bare |
| 121 | + except handlers in earlier versions of Python. |
| 122 | + |
| 123 | +A tool will be provided to automatically update code to replace bare ``except:`` |
| 124 | +with ``except BaseException:``. |
| 125 | + |
| 126 | + |
| 127 | +Security Implications |
| 128 | +===================== |
| 129 | + |
| 130 | +This change has no security implications. |
| 131 | + |
| 132 | + |
| 133 | +How to Teach This |
| 134 | +================= |
| 135 | + |
| 136 | +For new Python users, exception handling should be taught with explicit |
| 137 | +exception types from the start: |
| 138 | + |
| 139 | +.. code-block:: python |
| 140 | +
|
| 141 | + try: |
| 142 | + result = risky_operation() |
| 143 | + except ValueError: |
| 144 | + handle_value_error() |
| 145 | + except TypeError: |
| 146 | + handle_type_error() |
| 147 | + except Exception as e: |
| 148 | + handle_unexpected_error(e) |
| 149 | +
|
| 150 | +For experienced users, the change can be introduced as a best practice that is |
| 151 | +now enforced by the language. The following points should be emphasized: |
| 152 | + |
| 153 | +1. Always catch specific exceptions when possible. |
| 154 | +2. Use ``except Exception:`` as a last resort for truly unexpected errors. |
| 155 | +3. Never silence exceptions without careful consideration. |
| 156 | + |
| 157 | +Documentation should guide common exception hierarchies and how to choose |
| 158 | +appropriate exception types to catch. |
| 159 | + |
| 160 | +Rejected ideas |
| 161 | +============== |
| 162 | + |
| 163 | +* There are genuine cases where the use of bare ``except:`` handlers are correct. one |
| 164 | + of the examples that have been raised from Mailman [8]_ involves handling transactions |
| 165 | + in the face of any exception: |
| 166 | + |
| 167 | + .. code-block:: python |
| 168 | +
|
| 169 | + @contextmanager |
| 170 | + def transaction(): |
| 171 | + """Context manager for ensuring the transaction is complete.""" |
| 172 | + try: |
| 173 | + yield |
| 174 | + except: |
| 175 | + config.db.abort() |
| 176 | + raise |
| 177 | + else: |
| 178 | + config.db.commit() |
| 179 | +
|
| 180 | + This code guarantees that no matter what exception occurs, any open |
| 181 | + transaction will be aborted, while in the successful condition, the |
| 182 | + transaction will be committed. |
| 183 | + |
| 184 | + We do believe that although there are cases such like this one where |
| 185 | + bare ``except:`` handlers are correct, it would be better to actually |
| 186 | + be explicit and use ``except BaseException:`` for the reasons indicated |
| 187 | + in the "Motivation" section. |
| 188 | + |
| 189 | + |
| 190 | +Copyright |
| 191 | +========= |
| 192 | + |
| 193 | +This document is placed in the public domain or under the |
| 194 | +CC0-1.0-Universal license, whichever is more permissive. |
| 195 | + |
| 196 | +.. [1] https://pylint.pycqa.org/en/latest/user_guide/messages/warning/bare-except.html |
| 197 | +.. [2] https://www.flake8rules.com/rules/E722.html |
| 198 | +.. [3] https://docs.astral.sh/ruff/rules/bare-except/ |
| 199 | +.. [4] https://google.github.io/styleguide/pyguide.html#24-exceptions |
| 200 | +.. [5] https://chromium.googlesource.com/chromiumos/platform/factory/+/HEAD/CODING_STYLE.md#Avoid-bare_except |
| 201 | +.. [6] https://4.docs.plone.org/develop/plone-coredev/style.html#concrete-rules |
| 202 | +.. [7] https://docs.openedx.org/en/latest/developers/references/developer_guide/style_guides/python-guidelines.html |
| 203 | +.. [8] https://gitlab.com/mailman/mailman/-/blob/master/src/mailman/database/transaction.py#L27 |
| 204 | +
|
0 commit comments