-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added try-except-raise message example (#6540)
Co-authored-by: Vladyslav Krylasov <vladyslav.krylasov@gmail.com> Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com> Co-authored-by: Jacob Walls <jacobtylerwalls@gmail.com>
- Loading branch information
1 parent
f020b2f
commit cec1c6a
Showing
3 changed files
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
try: | ||
1 / 0 | ||
except ZeroDivisionError as e: # [try-except-raise] | ||
raise |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
There is a legitimate use case for re-raising immediately. E.g. with the following inheritance tree:: | ||
|
||
+-- ArithmeticError | ||
+-- FloatingPointError | ||
+-- OverflowError | ||
+-- ZeroDivisionError | ||
|
||
The following code shows valid case for re-raising exception immediately:: | ||
|
||
def execute_calculation(a, b): | ||
try: | ||
return some_calculation(a, b) | ||
except ZeroDivisionError: | ||
raise | ||
except ArithmeticError: | ||
return float('nan') | ||
|
||
The pylint is able to detect this case and does not produce error. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
# The try except might be removed entirely: | ||
1 / 0 | ||
|
||
# Or another more detailed exception can be raised: | ||
try: | ||
1 / 0 | ||
except ZeroDivisionError as e: | ||
raise ValueError("The area of the rectangle cannot be zero") from e |