Tryexcept代码块需要优化

2024-10-01 04:57:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面,我有一个try-except块,我想重构它。如您所见,它不是Python式的,并且不可维护。在

 try:
     try:
         foo()
     except xError:
         doSth()
         raise
 except:
     exc_type = sys.exc_info()[0]
     if exc_type == FooError:
         doBlaBla()
     else:   
         doFlaFla() 

     blablabla()       # whatever the exceptions is, run this code block
     foobar()
     zoo()
     ...        

我将该块更改为下面的代码

^{pr2}$

如你所见,我需要一个除了最后的类操作。它不会在没有异常但引发任何异常时运行。你有什么建议?我该怎么换这个土块?在


Tags: infoiffootypesyselse重构exc
3条回答

你为什么要用免责块? 在我看来,一个好的做法是把最后一个例外陈述,这样会捕捉到意想不到的错误。在

所以我建议:

try:
    fn()
except Exception1:
    do stuff you want
except Exception 2:
    do another stuff
except Exception as e:
    # Here you will catch an unexpected error, and you can log it
    raise UnknownError -> do stuff you want

可以将异常代码包装在try finally块中,例如:

try:
    try:
        foo()
    except xError:
        doSth()
        raise
# catch Exception to avoid catching system errors
except Exception as e:
    try:
        if isinstance(e, FooError):
            doBlaBla()
        else:   
            doFlaFla() 
            raise
    finally:
        # this will always run regardless of what you raise

另一种方法可以是这样的:

^{pr2}$

为什么不是这样的:

def others():
    """Other stuff to do when non-xError occurs.""" 
    blablabla()
    foobar()
    zoo()

然后将其分解成一个try

^{pr2}$

空的exceptusually a bad idea。在

相关问题 更多 >