Skip to content

[3.10] bpo-44305: Improve syntax error for try blocks without except … #26524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Doc/whatsnew/3.10.rst
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,20 @@ have been incorporated. Some of the most notable ones:

(Contributed by Pablo Galindo in :issue:`43823`)

* ``try`` blocks without ``except`` or ``finally`` blocks:

.. code-block:: python

>>> try
... x = 2
... something = 3
File "<stdin>", line 3
something = 3
^^^^^^^^^
SyntaxError: expected 'except' or 'finally' block

(Contributed by Pablo Galindo in :issue:`44305`)

* Usage of ``=`` instead of ``==`` in comparisons:

.. code-block:: python
Expand Down
1 change: 1 addition & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,7 @@ invalid_with_stmt_indent:
invalid_try_stmt:
| a='try' ':' NEWLINE !INDENT {
RAISE_INDENTATION_ERROR("expected an indented block after 'try' statement on line %d", a->lineno) }
| 'try' ':' block !('except' | 'finally') { RAISE_SYNTAX_ERROR("expected 'except' or 'finally' block") }
invalid_except_stmt:
| 'except' a=expression ',' expressions ['as' NAME ] ':' {
RAISE_SYNTAX_ERROR_STARTING_FROM(a, "multiple exception types must be parenthesized") }
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,14 @@
Traceback (most recent call last):
SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
Custom error messages for try blocks that are not followed by except/finally
>>> try:
... x = 34
...
Traceback (most recent call last):
SyntaxError: expected 'except' or 'finally' block
Ensure that early = are not matched by the parser as invalid comparisons
>>> f(2, 4, x=34); 1 $ 2
Traceback (most recent call last):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve error message for ``try`` blocks without ``except`` or ``finally``
blocks. Patch by Pablo Galindo.
Loading