python - 避免嵌套的 try/except
问题描述
我有以下代码结构:
try:
x = function_one(args)
try:
y = function_two(args)
try:
#
# some code where I need x and y
#
except Exception as e::
print("Problem with code above : ", e)
except Exception as e:
print("Problem with function_two : ", e)
#
# some code here
#
except Exception as e:
print("Problem with function_one : ", e)
它有效,但我想知道我是否可以避免这种嵌套的尝试/异常?例如,如果 x 为空并且之后不能使用,最好将 try / except 放在 function_one 中并找到一个解决方案来检查我是否可以将 x 用于其余代码,如果不能,则停止代码 ?我可以做一个if x something
,但它也会创建嵌套部分。
解决方案
如果您只使用 try\except 检查某个代码块,则可以将该块包装在处理程序中:
try:
x = function_one(args)
except Exception as e:
print("Problem with function_one : ", e)
try:
y = function_two(args)
except Exception as e:
print("Problem with function_two : ", e)
try:
#
# some code where I need x and y
#
except Exception as e::
print("Problem with code above : ", e)
try:
#
# some code here
#
except Exception as e::
print("Problem with code above : ", e)
通常,如果您打算在内部块中处理更具体的错误,则仅嵌套异常块。
推荐阅读
- php - 链接的 href 动态生成不适用于 php。打印但不起作用
- java - 从 RecyclerView 适配器类调用 Activity 中的方法
- azure - PEM 证书的 Azure B2C RSA 公钥
- python - 正则表达式 - 仅当前后有空格时才拆分字符
- arrays - 如何使用 jq 从 JSON 数组中提取特定字段
- python - 包含矩阵和向量的动态列表/数组
- excel - 可以通过公式定义自定义格式(不使用VBA)
- git - Azure DevOps:将拉取请求限制为团队的子集
- angular - 当在 Http.get 的 url 中发送 url 参数时,http GET 请求的 URL 被切断
- selenium-webdriver - 按属性匹配元素以 WebDriverIO 结尾