如何在 python3.7 中正确使用嵌套 try except?

How to use nested try except properly in python3.7?

我有这样的情况,我想 运行 一些代码行,如果这些行 运行 成功,那么 运行 另外几行。在这两种情况下都有 errors/exceptions 的可能性。所以我想知道在下面提到的两个之间使用 try catch 的最佳方法是什么

def function_name1():
    try:
        *Run first few lines*
        try:
            *Run second few lines*
        except Exception as ex2:
            raise Exception("second Exception - wdjk")
    except Exception as ex1:
        raise Exception("first Exception - wejk")

def function_name2():
    try:
        *Run first few lines*
    except Exception as ex1:
        raise Exception("first Exception - wejk")
    try:
        *Run second few lines*
    except Exception as ex2:
        raise Exception("second Exception - wdjk")

在 function_name1 中,我遇到了一个问题,即即使我在第二行得到异常,即 raise Exception("second Exception - wdjk"),代码正在返回或从 raise Exception("first Exception - wejk") 引发异常。 那么处理这种情况的最佳方法是什么?

最干净的解决方案是 运行 第一个 else 套件中的第二个 try/except

try:
    # first stuff
except SomeException:
    # error handling
else:  # no error occurred
    try:
        # second stuff
    except OtherException:
        # more error handling

如果代码块彼此独立,我不明白你为什么要嵌套它们。第二种选择会更好。您可以在 Real Python 的 post 中了解有关异常的更多信息:https://realpython.com/python-exceptions/ 他们讨论了 try-except 的工作原理。