假设我有以下代码,分配 > res
start end
1 2020-12-26 10:00:30 2020-12-26 10:01:00
2 2020-12-26 10:02:00 2020-12-26 10:02:00
3 2020-12-26 10:02:45 2020-12-26 10:03:30
并打印它,以防值为 1
或不是负数。
None
有没有办法避免重复两次分配value = None
class NegativeNumber(Exception):
pass
class NotFound(Exception):
pass
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
except NotFound:
value = 1
print(value)
else:
value = 1
print(value)
并打印出来?
像 value=1
这样的东西会很理想,但我在 python 中没有发现任何类似的东西。
答案 0 :(得分:1)
没有 except ... or else:
构造。抑制 try
块内的异常以触发异常的 else
块:
try:
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NotFound:
pass # suppress exception
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)
可以使用 contextlib.suppress
代替使用 try
/except
来抑制异常。这可以使意图更清晰,因为它明确指定了如何处理异常。
try:
with suppress(NotFound):
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)