简体   繁体   English

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

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

I have situation where I wanted to run some line of code and if those lines runs successfully then run another few lines.我有一种情况,我想运行一些代码行,如果这些行成功运行,则再运行几行。 In both cases there are possibilities of errors/exceptions.在这两种情况下,都有可能出现错误/异常。 So I wanted to know which would be the best way to use try catch between two I mentioned below所以我想知道在下面提到的两个之间使用 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")

In function_name1, I faced one issue that even if I get excption in second line ie raise Exception("second Exception - wdjk") , code is returning or raising exception from raise Exception("first Exception - wejk") .在 function_name1 中,我遇到了一个问题,即使我在第二行中得到了异常,即raise Exception("second Exception - wdjk") ,代码也会从raise Exception("first Exception - wejk")返回或引发异常。 So what would be the best way to handle this case?那么处理这种情况的最佳方法是什么?

The cleanest solution would be to run the second try/except in the else suite of the first:最干净的解决方案是在第一个的else套件中运行第二个try/except

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

If the code blocks are independent from one another, I don't see why you would nest them.如果代码块彼此独立,我不明白您为什么要嵌套它们。 The second option would be better.第二种选择会更好。 You can learn more about exceptions in this post by Real Python: https://realpython.com/python-exceptions/ There they talk about how try-except works.您可以在 Real Python 的这篇文章中了解有关异常的更多信息: https : //realpython.com/python-exceptions/在那里他们讨论了 try-except 的工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM