关于python:在一行中捕获多个异常(块除外)

Catch multiple exceptions in one line (except block)

我知道我能做到:

1
2
3
4
try:
    # do something that may fail
except:
    # do this if ANYTHING goes wrong

我也可以这样做:

1
2
3
4
5
6
try:
    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreTooShortException:
    # stand on a ladder

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

1
2
3
4
5
6
try:
    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreBeingMeanException:
    # say please

我有什么办法可以这样做吗(因为在两种例外情况下采取的行动都是针对say please)

1
2
3
4
try:
    # do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
    # say please

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

1
2
3
4
try:
    # do something that may fail
except Exception, e:
    # say please

所以,我试图捕捉这两个截然不同的异常并没有完全实现。

有办法吗?


在Python文档:

An except clause may name multiple exceptions as a parenthesized tuple, for example

1
2
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

或者,2只:Python for

1
2
except (IDontLikeYouException, YouAreBeingMeanException), e:
    pass

从变分捡一个例外,即想在Python 2.6和2.7安静的工作,但现在是过时的和不工作在Python 3 as;现在你应该使用。


How do I catch multiple exceptions in one line (except block)

这样做:

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

周围的括号是必需的,由于旧的语法,使用逗号来分配到一个错误的对象的名称。这是as关键字用于赋值。你可以使用任何名称的错误对象,我喜欢error个人。

最佳实践

这样做的人,目前在A和前向兼容Python的异常处理程序,你需要一个逗号和分离他们从一包到differentiate括号语法实例都是由一个变量名的例外的例外是夹式的一个逗号。

这是一个简单的例子:在大学。

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

我只从指定异常处理程序以避免隐藏的bug,如果我遇到一个没有完整的堆栈跟踪。

这是记录在这里:http:/ / / / docs.python.org教程的链接。

你可以指定一个变量(例外,e是普通,但你可能会喜欢,如果你有更详细的异常处理变长或您的IDE使用的唯一亮点是什么装修,为矿山的实例。)有一个属性。这里是一个例子:

1
2
3
4
5
6
try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err:
    print(err)
    print(err.args)
    quit(0)

注意Python对象3,如err范围外except块是在结束了。

过时的

你可以在代码assigns湖是一个逗号错误。这是唯一可用的形式使用,Python 2.5和更早的,是过时的,如果你希望你的代码和一个前锋在Python 3兼容,你应该更新使用新的语法形式:

1
2
3
4
5
6
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线的代码,最小:

1
2
3
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

tryexceptpass线,可以在单路A线,且与上下文经理可在Python:3.4

1
2
3
4
from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

所以当你想在某些suppresspass异常的使用。


和早期版本的Python 2.5的,正确的语法是:

1
2
except (IDontLikeYouException, YouAreBeingMeanException), e:
    print e

e是异常实例。


在Python文档> 8.3处理异常处理程序:

A try statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be
executed. Handlers only handle exceptions that occur in the
corresponding try clause, not in other handlers of the same try
statement. An except clause may name multiple exceptions as a
parenthesized tuple, for example:

1
2
except (RuntimeError, TypeError, NameError):
    pass

Note that the parentheses around this tuple are required, because
except ValueError, e: was the syntax used for what is normally
written as except ValueError as e: in modern Python (described
below). The old syntax is still supported for backwards compatibility.
This means except RuntimeError, TypeError is not equivalent to
except (RuntimeError, TypeError): but to except RuntimeError as
TypeError: which is not what you want.


如果你经常使用一个大的数量的异常处理程序,你可以预先定义a元组,所以你不重型他们多次。

1
2
3
4
5
6
7
8
9
10
11
12
13
#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

说明:

  • 如果你需要其他的,因此,比那些在抛出异常的catch预先确定的元组,你将需要定义一个块的形式。

  • 如果你只是不能容忍把全局变量不能定义它,在main()和它需要护照在哪里……


  • 一个一个的方式这样做。

    1
    2
    3
    4
    5
    6
    7
    8
    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块写的。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    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]

    我不知道第二个最好的方式这样做,但我只是一个数字显示的方式做这件事。


    Python 2.7新文档:

    A try statement may have more than one except clause, to specify
    handlers for different exceptions. At most one handler will be
    executed. Handlers only handle exceptions that occur in the
    corresponding try clause, not in other handlers of the same try
    statement. An except clause may name multiple exceptions as a
    parenthesized tuple, for example:

    1
    2
    3
    4
    try:
        raise ValueError("hello")
    except (RuntimeError, ValueError, KeyError) as a:
        print a

    Note
    that the parentheses around this tuple are required, because except
    ValueError, e: was the syntax used for what is normally written as
    except ValueError as e: in modern Python (described below). The old
    syntax is still supported for backwards compatibility. This means
    except RuntimeError, TypeError is not equivalent to except
    (RuntimeError, TypeError): but to except RuntimeError as TypeError:
    which is not what you want.