← 中文资源

简体中文版本

自定义异常层次设计

设计小型异常层次:调用方可笼统或精确捕获,raise…from 保留原始 traceback 链不丢根因。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

validation: quantity is not a number: 'abc' | cause: ValueError
external: inventory service timed out | cause: TimeoutError

实现说明

逻辑集中在类 AppError、ValidationError、ExternalServiceError和函数 parse_quantity、fetch_inventory、main里。 for fn in (lambda: parse_quantity('abc'), fetch_inventory) 承担全部的逐项处理。ValidationError、TimeoutError、ExternalServiceError 出现在 except 处理器内部——只在该失败类型已被处理时才抛出。

使用要点

  • 跑完文件,输出里会留下标记——validation:、external:。
  • main 按顺序串起 parse_quantity;运行文件就会把这个流程跑一遍。

常见问题

异常在什么时候抛出?

在 except 处理器内部——ValidationError、TimeoutError、ExternalServiceError 只在该失败类型已被触发处理时才会抛出,没有独立的触发条件。

运行「自定义异常层次设计」会打印什么?

运行文件本身,validation:、external: 这些前缀各对应一段演示逻辑。

入口签名:def parse_quantity(raw: str) -> int

核心语句

def parse_quantity(raw: str) -> int:
    try:
        return int(raw)
    except ValueError as exc:
        # raise ... from exc:保留原始 traceback 链
        raise ValidationError(f'quantity is not a number: {raw!r}') from exc
except ExternalServiceError as exc:
    print('external:', exc, '| cause:', type(exc.__cause__).__name__)
except ValidationError as exc:
    print('validation:', exc, '| cause:', type(exc.__cause__).__name__)

代码示例

class AppError(Exception):
    """应用异常基类:调用方可笼统捕获。"""


class ValidationError(AppError):
    """输入不合法。"""


class ExternalServiceError(AppError):
    """下游依赖失败。"""


def parse_quantity(raw: str) -> int:
    try:
        return int(raw)
    except ValueError as exc:
        # raise ... from exc:保留原始 traceback 链
        raise ValidationError(f'quantity is not a number: {raw!r}') from exc


def fetch_inventory() -> int:
    try:
        raise TimeoutError('upstream slow')
    except TimeoutError as exc:
        raise ExternalServiceError('inventory service timed out') from exc


def main() -> None:
    for fn in (lambda: parse_quantity('abc'), fetch_inventory):
        try:
            fn()
        except ValidationError as exc:
            print('validation:', exc, '| cause:', type(exc.__cause__).__name__)
        except ExternalServiceError as exc:
            print('external:', exc, '| cause:', type(exc.__cause__).__name__)
        except AppError as exc:
            print('generic app error:', exc)


if __name__ == '__main__':
    main()