嵌套在Python中的try / except [英] nested try/except in Python
问题描述
try:
commands
try:
commands
try:
commands
try:
commands
except:
commands
return to final commands
except:
commands
return to final commands
except:
commands
return to final commands
except:
commands
final commands
我要写哪个指令代替返回到最终命令
,使除以外的任何$ 返回外部尝试后的顶级指令?
Which instruction have I to write in place of return to final commands
to make that any except
returns to the top-level instructions following the outer try? And is it an acceptable structure?
编辑:这是一个玩具示例(我知道我可以使用 if
s,这只是一个示例;假设您必须使用 try
/ /
除外)来编写它。
Here is a toy example (I know I can do it using if
s, it's only an example; suppose you have to write it using try
/except
).
# calculate arcsin(log(sqrt(x)-4))
x = choose one yourself
try
x1=sqrt(x)
return to final message
try
x1=log(x1-4)
return to final message
try
x2=arcsin(x1)
return to final message
except
message="Impossible to calculate arcsin: maybe an argument outside [-1,+1]?"
except
message="Impossible to calculate logarithm: maybe a not positive argument?"
except
message="impossible to calculate square root: maybe a negative argument?"
final message:
print message
推荐答案
至少,您应该能够通过引发异常来避免该块的其余部分,从而将该结构减少到仅两个嵌套级别:
At the very least you should be able to reduce this structure to only 2 nested levels by reraising the exception to avoid the rest of the block:
# 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将位于更高级别的函数中:
Really, this is not the way to do it, at least in this example. The problem is that you are trying to use exceptions like return error codes. What you should be doing is putting the error message into the exception. Also, normally the outer try/except would be in a higher level function:
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
这篇关于嵌套在Python中的try / except的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!