Let’s say I have the following code, that assign 1
and print it in case the value is None
or not negative.
JavaScript
x
21
21
1
value = None
2
3
class NegativeNumber(Exception):
4
pass
5
class NotFound(Exception):
6
pass
7
8
try:
9
if value is None:
10
raise NotFound
11
elif value < 0:
12
raise NegativeNumber
13
except NegativeNumber:
14
print("Error: negative number")
15
except NotFound:
16
value = 1
17
print(value)
18
else:
19
value = 1
20
print(value)
21
Is there a way to avoid repeat twice to assign value=1
and print it?
It would be ideal something like except NotFound or else
, but I have not found anything similar in python.
Advertisement
Answer
There is no except ... or else:
construct. Suppress the exception inside the try
block to trigger the else
block for the exception as well:
JavaScript
1
14
14
1
try:
2
try:
3
if value is None:
4
raise NotFound
5
elif value < 0:
6
raise NegativeNumber
7
except NotFound:
8
pass # suppress exception
9
except NegativeNumber:
10
print("Error: negative number")
11
else:
12
value = 1
13
print(value)
14
Instead of using try
/except
to suppress the exception, contextlib.suppress
can be used instead. This can make the intention clearer, as it explicitly names how the exception is handled.
JavaScript
1
12
12
1
try:
2
with suppress(NotFound):
3
if value is None:
4
raise NotFound
5
elif value < 0:
6
raise NegativeNumber
7
except NegativeNumber:
8
print("Error: negative number")
9
else:
10
value = 1
11
print(value)
12