当前位置:   article > 正文

python try里面嵌套try_Python中的嵌套try/except

try except 里面能嵌套 try

通过重新引发异常以避免块的其余部分,您至少应该能够将此结构减少到仅两个嵌套级别:# 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/笔触狂放9/article/detail/631454?site
推荐阅读
相关标签
  

闽ICP备14008679号