当前位置:   article > 正文

python中的try能嵌套吗_在Python中嵌套try / except

python try嵌套

至少你应该能够通过重新添加异常来将此结构减少到只有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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/631441
推荐阅读
相关标签
  

闽ICP备14008679号