python - 避免嵌套尝试/异常(exception)

标签 python python-3.x error-handling

我有以下代码结构:

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/

相关文章:

python - 在没有安装 Python 的情况下,mercurial 如何工作?

python - TypeError - python 中的客户端错误

python - Python 中 if/else 语句错误中不支持的操作数

python - 在数据框中执行行乘法

python - 如何在Python中根据日期的概率生成随机日期?

asp.net-mvc - 是否可以在MVC网站上使用自定义错误页面,但不能在Web API上使用?

date - 将 datetime.now().date() 与 Python 中的日期常量进行比较

python-3.x - 子图的通用 x 标签

运行 NLTK StanfordParser 时 Java 命令失败

ruby-on-rails - Ruby - 具有不同参数的重试函数