Skip to content

Commit e53f72a

Browse files
authored
[3.10] bpo-44305: Improve syntax error for try blocks without except or finally (GH-26523) (GH-26524)
(cherry picked from commit b250f89) Co-authored-by: Pablo Galindo <[email protected]>
1 parent 3283bf4 commit e53f72a

File tree

5 files changed

+383
-269
lines changed

5 files changed

+383
-269
lines changed

Doc/whatsnew/3.10.rst

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,20 @@ have been incorporated. Some of the most notable ones:
274274
275275
(Contributed by Pablo Galindo in :issue:`43823`)
276276
277+
* ``try`` blocks without ``except`` or ``finally`` blocks:
278+
279+
.. code-block:: python
280+
281+
>>> try
282+
... x = 2
283+
... something = 3
284+
File "<stdin>", line 3
285+
something = 3
286+
^^^^^^^^^
287+
SyntaxError: expected 'except' or 'finally' block
288+
289+
(Contributed by Pablo Galindo in :issue:`44305`)
290+
277291
* Usage of ``=`` instead of ``==`` in comparisons:
278292
279293
.. code-block:: python

Grammar/python.gram

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,6 +964,7 @@ invalid_with_stmt_indent:
964964
invalid_try_stmt:
965965
| a='try' ':' NEWLINE !INDENT {
966966
RAISE_INDENTATION_ERROR("expected an indented block after 'try' statement on line %d", a->lineno) }
967+
| 'try' ':' block !('except' | 'finally') { RAISE_SYNTAX_ERROR("expected 'except' or 'finally' block") }
967968
invalid_except_stmt:
968969
| 'except' a=expression ',' expressions ['as' NAME ] ':' {
969970
RAISE_SYNTAX_ERROR_STARTING_FROM(a, "multiple exception types must be parenthesized") }

Lib/test/test_syntax.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -882,6 +882,14 @@
882882
Traceback (most recent call last):
883883
SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
884884
885+
Custom error messages for try blocks that are not followed by except/finally
886+
887+
>>> try:
888+
... x = 34
889+
...
890+
Traceback (most recent call last):
891+
SyntaxError: expected 'except' or 'finally' block
892+
885893
Ensure that early = are not matched by the parser as invalid comparisons
886894
>>> f(2, 4, x=34); 1 $ 2
887895
Traceback (most recent call last):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve error message for ``try`` blocks without ``except`` or ``finally``
2+
blocks. Patch by Pablo Galindo.

0 commit comments

Comments
 (0)