Python 中 except 语句的顺序

5 投票
2 回答
3624 浏览
提问于 2025-04-18 05:23

如果我有一个异常类的继承结构,在一个try块中,如果我想先处理一个更具体(派生)的异常,再处理一个更一般的异常,我是不是只需要把针对派生类的except语句放在基类的上面就可以了?

这样做可以吗?

class MyException(BaseException):
    pass

class AnotherException(MyException):
    pass

try:
    raise AnotherException()
except AnotherException:
    print('Caught YetAnotherException!')
except MyException:
    print('Caught MyException!')

print('Done.')

我试过了,确实有效,但我很惊讶找不到相关的文档说明。

2 个回答

-4

这是一些常用的异常处理语句,通常和try语句一起使用。

**except: Catch all (or all other) exception types.
**except name: Catch a specific exception only.
**except name as value: Catch the listed exception and assign its instance.
**except (name1, name2): Catch any of the listed exceptions.
**except (name1, name2) as value: Catch any listed exception and assign its instance.
**else: Run if no exceptions are raised in the try block.
**finally: Always perform this block on exit.
7

可以看看Python语言参考中的try语句的文档。相关的内容是:

当在try代码块中发生错误时,程序会开始寻找处理这个错误的方法。它会一个一个检查except部分,直到找到一个能处理这个错误的地方。

撰写回答