Skip to content

Commit cec1c6a

Browse files
matusvalosprytnykPierre-Sassoulasjacobtylerwalls
authored
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>
1 parent f020b2f commit cec1c6a

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
try:
2+
1 / 0
3+
except ZeroDivisionError as e: # [try-except-raise]
4+
raise
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
There is a legitimate use case for re-raising immediately. E.g. with the following inheritance tree::
2+
3+
+-- ArithmeticError
4+
+-- FloatingPointError
5+
+-- OverflowError
6+
+-- ZeroDivisionError
7+
8+
The following code shows valid case for re-raising exception immediately::
9+
10+
def execute_calculation(a, b):
11+
try:
12+
return some_calculation(a, b)
13+
except ZeroDivisionError:
14+
raise
15+
except ArithmeticError:
16+
return float('nan')
17+
18+
The pylint is able to detect this case and does not produce error.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# The try except might be removed entirely:
2+
1 / 0
3+
4+
# Or another more detailed exception can be raised:
5+
try:
6+
1 / 0
7+
except ZeroDivisionError as e:
8+
raise ValueError("The area of the rectangle cannot be zero") from e

0 commit comments

Comments
 (0)