Skip to content

Commit d8c385a

Browse files
committed
gh-134036: Improve error messages for invalid raise statements
1 parent 7eaa097 commit d8c385a

File tree

4 files changed

+529
-402
lines changed

4 files changed

+529
-402
lines changed

Grammar/python.gram

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ return_stmt[stmt_ty]:
184184
| 'return' a=[star_expressions] { _PyAST_Return(a, EXTRA) }
185185

186186
raise_stmt[stmt_ty]:
187+
| invalid_raise_stmt
187188
| 'raise' a=expression b=['from' z=expression { z }] { _PyAST_Raise(a, b, EXTRA) }
188189
| 'raise' { _PyAST_Raise(NULL, NULL, EXTRA) }
189190

@@ -1287,6 +1288,11 @@ invalid_ann_assign_target[expr_ty]:
12871288
| list
12881289
| tuple
12891290
| '(' a=invalid_ann_assign_target ')' { a }
1291+
invalid_raise_stmt:
1292+
| a='raise' b='from' {
1293+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "did you forget an expression between 'raise' and 'from'?") }
1294+
| 'raise' expression a='from' {
1295+
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "did you forget an expression after 'from'?") }
12901296
invalid_del_stmt:
12911297
| 'del' a=star_expressions {
12921298
RAISE_SYNTAX_ERROR_INVALID_TARGET(DEL_TARGETS, a) }

Lib/test/test_syntax.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1678,6 +1678,28 @@
16781678
...
16791679
SyntaxError: invalid syntax
16801680
1681+
Better errors for `raise` statement:
1682+
1683+
>>> raise ValueError from
1684+
Traceback (most recent call last):
1685+
SyntaxError: did you forget an expression after 'from'?
1686+
1687+
>>> raise mod.ValueError() from
1688+
Traceback (most recent call last):
1689+
SyntaxError: did you forget an expression after 'from'?
1690+
1691+
>>> raise from exc
1692+
Traceback (most recent call last):
1693+
SyntaxError: did you forget an expression between 'raise' and 'from'?
1694+
1695+
>>> raise from None
1696+
Traceback (most recent call last):
1697+
SyntaxError: did you forget an expression between 'raise' and 'from'?
1698+
1699+
>>> raise from
1700+
Traceback (most recent call last):
1701+
SyntaxError: did you forget an expression between 'raise' and 'from'?
1702+
16811703
Check that an multiple exception types with missing parentheses
16821704
raise a custom exception only when using 'as'
16831705
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :exc:`SyntaxError` message when using invalid :keyword:`raise`
2+
statements.

0 commit comments

Comments
 (0)