Python中的异常语句顺序排列

2024-10-03 04:32:56 发布

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

如果我有一个异常类的继承层次结构,并且在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.')

我已经试过了,而且很有效,但是我很惊讶我找不到任何关于这个的文档。在


Tags: 层次结构pass语句基类classraiseprinttry
2条回答

查看Python语言参考中^{} statement的文档。相关位为:

When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception.

一些常用的异常子句形式带有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.

相关问题 更多 >