Skip to content

Commit 0d9ccc8

Browse files
authored
gh-134036: Improve error messages for invalid raise statements (#134077)
1 parent a7d41e8 commit 0d9ccc8

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
@@ -1695,6 +1695,28 @@
16951695
...
16961696
SyntaxError: invalid syntax
16971697
1698+
Better errors for `raise` statement:
1699+
1700+
>>> raise ValueError from
1701+
Traceback (most recent call last):
1702+
SyntaxError: did you forget an expression after 'from'?
1703+
1704+
>>> raise mod.ValueError() from
1705+
Traceback (most recent call last):
1706+
SyntaxError: did you forget an expression after 'from'?
1707+
1708+
>>> raise from exc
1709+
Traceback (most recent call last):
1710+
SyntaxError: did you forget an expression between 'raise' and 'from'?
1711+
1712+
>>> raise from None
1713+
Traceback (most recent call last):
1714+
SyntaxError: did you forget an expression between 'raise' and 'from'?
1715+
1716+
>>> raise from
1717+
Traceback (most recent call last):
1718+
SyntaxError: did you forget an expression between 'raise' and 'from'?
1719+
16981720
Check that an multiple exception types with missing parentheses
16991721
raise a custom exception only when using 'as'
17001722
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)