我如何区分同一审判状态中发生的不同例外

2024-10-02 16:31:36 发布

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

例如:

try:
    myfruits = FruitFunction()    #Raises some exception (unknown)
    assert "orange" in myfruits   #Raises AssertionError (known)

except:
    # I don't know how to distinguish these two errors :(

我需要从所有未知的异常中筛选出一种特殊的异常(已知的)。我还需要断言来继续同样的异常处理

^{pr2}$

为了更简洁地传达这一观点,我将添加一个真实的例子:

try:
    # This causes all sorts of errors
    myurl = urllib.urlopen(parametes)

    # But if everything went well
    assert myurl.status == 202

    # proceed normal stuff

except:
    # print "An error occured" if any error occured
    # but if it was an assertion error,
    # add "it was something serious too!"

Tags: ifexceptioniterrorsomeasserttryraises
3条回答
try:
    try:
        myfruits = FruitFunction()    #Raises some exception (unknown)
        assert "orange" in myfruits   #Raises AssertionError (known)
    except AssertionError:
        # handle assertion
        raise
except Exception:
    # handle everything

我假设您不能将抛出不同异常的两个语句分开(例如,因为它们在另一个函数中一起关闭)。如果可以的话,以下内容将更加精确和直接:

^{pr2}$

它更精确,因为如果FruitFunction()引发的未知异常恰好是AssertionError,那么它就不会被捕获到内部try。如果不分离语句,就没有(合理的)方法来区分从两个不同位置抛出的同一类型的两个异常。因此,对于第一个代码,您最好希望FruitFunction()不会引发AssertionError,或者如果它发生了,那么可以用与另一个相同的方式处理。在

try:
    # Do something
    myurl = urllib.urlopen(parametes)
    assert myurl.status == 202
except Exception as e:
    # Handle Exception
    print('An error occured')
    if isinstance(e, AssertionError):
        # Handle AssertionError
        print('it was something serious too!')
else:
    # proceed normal stuff

如果它同时引发了一个未知异常和一个AssertionError,并且您需要同时处理这两个问题,那么应该使用两个单独的try语句。在

try:
    raise IndexError()
    assert 'orange' in myfruits
except AssertionError:
    print 'AssertionError'
except:
    print 'another error'

上面的方法只捕获第一个错误,而

^{pr2}$

将捕获两个错误。在

相关问题 更多 >