在一行中捕获多个异常(块除外)

时间:2011-06-24 15:55:09

标签: python exception exception-handling

我知道我能做到:

try:
    # do something that may fail
except:
    # do this if ANYTHING goes wrong

我也可以这样做:

try:
    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreTooShortException:
    # stand on a ladder

但如果我想在两个不同的例外中做同样的事情,我现在能想到的最好的就是这样做:

try:
    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreBeingMeanException:
    # say please

我有什么方法可以做这样的事情(因为两个例外的行动都是say please):

try:
    # do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
    # say please

现在这确实不起作用,因为它符合以下语法:

try:
    # do something that may fail
except Exception, e:
    # say please

所以,我努力捕捉到两个截然不同的例外并没有完全实现。

有办法做到这一点吗?

5 个答案:

答案 0 :(得分:3151)

来自Python Documentation

  

except子句可以将多个异常命名为带括号的元组,例如

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

或者,仅适用于Python 2:

except (IDontLikeYouException, YouAreBeingMeanException), e:
    pass

使用逗号将变量与变量分开仍然可以在Python 2.6和2.7中使用,但现在已弃用,但在Python 3中不起作用;现在你应该使用as

答案 1 :(得分:249)

  

如何在一行中捕获多个异常(块除外)

这样做:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

由于旧语法使用逗号将错误对象分配给名称,因此必须使用括号。 as关键字用于分配。您可以使用任何名称作为错误对象,我个人更喜欢error

最佳实践

要以与Python当前和向前兼容的方式执行此操作,您需要使用逗号分隔异常并用括号括起它们,以区别于将异常实例分配给变量名的早期语法,方法是遵循Exception类型抓住了一个逗号。

以下是一个简单用法示例:

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    quit(0)

我只是指定这些异常以避免隐藏错误,如果遇到错误,我希望从中获得完整的堆栈跟踪。

此处记录了这些内容:https://docs.python.org/tutorial/errors.html

您可以将异常分配给变量,(e是常见的,但如果您有长时间的异常处理,或者您的IDE仅突出显示大于该值的选择,您可能更喜欢更详细的变量,就像我的那样。)该实例具有args属性。这是一个例子:

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    quit(0)

请注意,在Python 3中,当err块结束时,except对象超出了范围。

已过时

您可能会看到用逗号分配错误的代码。这种用法是Python 2.5及更早版本中唯一可用的形式,不推荐使用,如果您希望代码在Python 3中向前兼容,则应更新语法以使用新表单:

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    quit(0)

如果您在代码库中看到逗号名称分配,并且您使用的是Python 2.5或更高版本,请切换到新方法,以便在升级时代码保持兼容。

suppress上下文管理器

接受的答案实际上是4行代码,最少:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

可以使用suppress context manager, available in Python 3.4在一行中处理tryexceptpass行:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

因此,当您想要pass某些例外情况时,请使用suppress

答案 2 :(得分:40)

来自Python documentation -> 8.3 Handling Exceptions

  

try语句可以有多个except子句来指定   不同例外的处理程序。最多只有一个处理程序   执行。处理程序只处理在中发生的异常   相应的try子句,不在同一尝试的其他处理程序中   声明。 except子句可以将多个异常命名为a   带括号的元组,例如:

except (RuntimeError, TypeError, NameError):
    pass
     

请注意,此元组周围的括号是必需的,因为   除了ValueError, e:是用于正常情况的语法   在现代Python中写成except ValueError as e:(描述   下面)。仍然支持旧语法以实现向后兼容性。   这意味着except RuntimeError, TypeError不等同于   except (RuntimeError, TypeError):但是except RuntimeError as   TypeError:这不是你想要的。

答案 3 :(得分:25)

如果您经常使用大量例外,则可以预先定义元组,因此您不必多次重新键入它们。

#This example code is a technique I use in a library that connects with websites to gather data

ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)

def connect(url, data):
    #do connection and return some data
    return(received_data)

def some_function(var_a, var_b, ...):
    try: o = connect(url, data)
    except ConnectErrs as e:
        #do the recovery stuff
    blah #do normal stuff you would do if no exception occurred

注意:

  1. 如果你还需要捕捉除了那些之外的其他例外情况 预定义的元组,你需要定义另一个除了块。

  2. 如果您无法容忍全局变量,请在main()中定义它 并在需要的地方传递......

答案 4 :(得分:9)

其中一种方法是......

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

另一种方法是创建执行由except块执行的任务的方法,并通过你写的所有except块调用它。

try:
   You do your operations here;
   ......................
except Exception1:
    functionname(parameterList)
except Exception2:
    functionname(parameterList)
except Exception3:
    functionname(parameterList)
else:
   If there is no exception then execute this block. 

def functionname( parameters ):
   //your task..
   return [expression]

我知道第二个不是最好的方法,但我只是展示了做这件事的方法。

相关问题