Skip to content

gh-134036: Improve error messages for invalid raise statements #134077

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 6, 2025
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
6 changes: 6 additions & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ return_stmt[stmt_ty]:
| 'return' a=[star_expressions] { _PyAST_Return(a, EXTRA) }

raise_stmt[stmt_ty]:
| invalid_raise_stmt
| 'raise' a=expression b=['from' z=expression { z }] { _PyAST_Raise(a, b, EXTRA) }
| 'raise' { _PyAST_Raise(NULL, NULL, EXTRA) }

Expand Down Expand Up @@ -1287,6 +1288,11 @@ invalid_ann_assign_target[expr_ty]:
| list
| tuple
| '(' a=invalid_ann_assign_target ')' { a }
invalid_raise_stmt:
| a='raise' b='from' {
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "did you forget an expression between 'raise' and 'from'?") }
| 'raise' expression a='from' {
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "did you forget an expression after 'from'?") }
invalid_del_stmt:
| 'del' a=star_expressions {
RAISE_SYNTAX_ERROR_INVALID_TARGET(DEL_TARGETS, a) }
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -1678,6 +1678,28 @@
...
SyntaxError: invalid syntax

Better errors for `raise` statement:

>>> raise ValueError from
Traceback (most recent call last):
SyntaxError: did you forget an expression after 'from'?

>>> raise mod.ValueError() from
Traceback (most recent call last):
SyntaxError: did you forget an expression after 'from'?

>>> raise from exc
Traceback (most recent call last):
SyntaxError: did you forget an expression between 'raise' and 'from'?

>>> raise from None
Traceback (most recent call last):
SyntaxError: did you forget an expression between 'raise' and 'from'?

>>> raise from
Traceback (most recent call last):
SyntaxError: did you forget an expression between 'raise' and 'from'?

Check that an multiple exception types with missing parentheses
raise a custom exception only when using 'as'

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve :exc:`SyntaxError` message when using invalid :keyword:`raise`
statements.
Loading
Loading