Python异常捕获中的布尔'not'

时间:2014-02-12 11:56:27

标签: python exception-handling

我尝试构造一个except子句,捕获除[sic]之外的所有异常类型的异常:

try:
    try:
        asdjaslk
    except not NameError as ne: #I want this block to catch everything except NameError
        print("!NameError- {0}: {1}".format(ne.__class__, ne))
except Exception as e: #NameError is the only one that should get here
    print("Exception- {0}: {1}".format(e.__class__, e))

该语言接受not子句中的except,但不对其执行任何操作:

>>> Exception- <type 'exceptions.NameError'>: name 'asdjaslk' is not defined

是否可以这样做,还是应该重新raise

2 个答案:

答案 0 :(得分:4)

你必须重新加注。 except语句只能列入白名单,而不能列入黑名单。

try:
    asdjaslk
except Exception as ne:
    if isinstance(ne, NameError):
        raise

not NameError表达式返回False,因此您基本上试图捕捉:

except False:

但是没有异常会匹配布尔实例。

语法允许任何有效的Python表达式,并且抛出的异常与该表达式的结果匹配。例如,except SomeException if debug else SomeOtherException:完全有效。

答案 1 :(得分:0)

你可以试试这个:

try:
    # your code raising exceptions

except NameError:
    # catch the exception you don't want to catch
    # but immediately raise it again:
    print("re-raising NameError- {0}: {1}".format(ne.__class__, ne))
    raise

except Exception as e:
    # handle all other exceptions here
    print("catching Exception- {0}: {1}".format(e.__class__, e))
    pass