我有以下代码结构:
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)
它有效,但是我想知道是否可以避免这种嵌套的try/exception?例如,如果x为空并且以后不能使用,那么最好将try/除外放入function_one内,并找到一种解决方案来检查我是否可以将x用于其余的代码,否则,请停止代码?
我可以做一个
if x something
,但它也会创建嵌套部分。
最佳答案
如果您的异常块没有执行某些功能(如果甚至在内部出现错误,则继续处理其余代码),则不应使用嵌套的try-catch块。相反,您可以编写一个更多的异常块。例如,
try:
x = function_one(args)
y = function_two(args)
except Exceptionx as e:
print("Problem with function_one : ", e)
except Exceptiony as e:
print("Problem with function_two : ", e)
Exceptionx和Exceptiony应该是Exception类对象,并且您应该知道将获得哪种异常。您可以在以下位置了解更多示例https://docs.python.org/3/tutorial/errors.html
关于python - 避免嵌套尝试/异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63283999/