赞
踩
通过重新引发异常以避免块的其余部分,您至少应该能够将此结构减少到仅两个嵌套级别:# calculate arcsin(log(sqrt(x)-4))
x = ?
message = None
try:
try:
x1 = sqrt(x)
except Exception:
message = "can't take sqrt"
raise
try:
x1 = log(x1-4)
except Exception:
message = "can't compute log"
raise
try:
x2 = arcsin(x1)
except Exception:
message = "Can't calculate arcsin"
raise
except Exception:
print message
实际上,至少在这个例子中,这不是实现它的方法。问题是您试图使用异常,如返回错误代码。您应该做的是将错误消息放入异常中。此外,通常外部try/except将处于更高级别的函数中:def func():
try:
y = calculate_asin_log_sqrt(x)
# stuff that depends on y goes here
except MyError as e:
print e.message
# Stuff that happens whether or not the calculation fails goes here
def calculate_asin_log_sqrt(x):
try:
x1 = sqrt(x)
except Exception:
raise MyError("Can't calculate sqrt")
try:
x1 = log(x1-4)
except Exception:
raise MyError("Can't calculate log")
try:
x2 = arcsin(x1)
except Exception:
raise MyError("Can't calculate arcsin")
return x2
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。