tic*_*tic 6 python exception-handling try-catch
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
Run Code Online (Sandbox Code Playgroud)
这说明有我在的地方写return to final commands作任何except返回到顶层指示以下外尝试一下呢?它是一个可接受的结构吗?
编辑:这是一个玩具示例(我知道我可以用ifs 做它,它只是一个例子;假设你必须用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
Run Code Online (Sandbox Code Playgroud)
Eva*_*van 23
至少你应该能够通过重新添加异常来将此结构减少到只有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
Run Code Online (Sandbox Code Playgroud)
真的,至少在这个例子中,这不是这样做的方法.问题是您正在尝试使用返回错误代码之类的异常.您应该做的是将错误消息放入异常中.此外,通常外部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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29359 次 |
| 最近记录: |