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

通过重新引发异常以避免块的其余部分,您至少应该能够将此结构减少到仅两个嵌套级别:# 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值