如何区分同一个try语句中出现的不同异常

3 python exception

例如:

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 :(
Run Code Online (Sandbox Code Playgroud)

我需要从所有其他未知的异常中过滤出一种特殊的异常(已知).我还需要断言来继续相同的异常处理,

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

except AssertionError:
    # Handle Assertion Errors here
    # But I want the except below to happen too!

except:
    # Handle everything here
Run Code Online (Sandbox Code Playgroud)

我将添加一个真实的例子来更简洁地传达这个想法:

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!"
Run Code Online (Sandbox Code Playgroud)

Ste*_*sop 5

try:
    try:
        myfruits = FruitFunction()    #Raises some exception (unknown)
        assert "orange" in myfruits   #Raises AssertionError (known)
    except AssertionError:
        # handle assertion
        raise
except Exception:
    # handle everything
Run Code Online (Sandbox Code Playgroud)

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

try:
    myfruits = FruitFunction()    #Raises some exception (unknown)
    try:
        assert "orange" in myfruits   #Raises AssertionError (known)
    except AssertionError:
        # handle assertion
        raise
except Exception:
    # handle everything
Run Code Online (Sandbox Code Playgroud)

它更精确,因为如果发生的未知异常FruitFunction()恰好是AssertionError那么它就不会陷入内心try.在不分离语句的情况下,没有(合理的)方法来区分从两个不同位置抛出的两个相同类型的异常.因此,对于第一个代码,您最好FruitFunction()不要提升AssertionError,或者如果确实如此,那么它可以像处理另一个代码一样处理.

  • 我试图避免嵌套 try-except 语句以提高可读性。如果我确实遵循这种模式,我最终会得到一个 5 到 6 步的嵌套代码!此外,断言而不是 if-else 语句也有助于可读性和线性编码。但是,非常感谢您的回答和时间。 (2认同)