赞
踩
至少你应该能够通过重新添加异常来将此结构减少到只有2个嵌套级别,以避免其余的块:
# 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 版权所有,并保留所有权利。