首页 > 解决方案 > 子类化异常有什么帮助?

问题描述

我没有直接调用异常,而是看到它被子类化,其中没有任何内容或pass语句。它如何帮助 Python 在内部以这种方式子类化基类?它会改变命名空间或签名吗?如何?

class ACustomException(Exception):
    pass

class BCustomException(Exception):
    pass

标签: pythoninheritanceexception

解决方案


提高Exception就像告诉医生“有问题”然后拒绝回答任何问题。比较:

try:
    with open("foo.json", "rt") as r:
        new_count = json.load(r)["count"] + 1
except Exception:
    # Is the file missing?
    # Is the file there, but not readable?
    # Is the file readable, but does not contain valid JSON?
    # Is the file format okay, but the data's not a dict with `count`?
    # Is the entry `count` there, but is not a number?
    print("Something's wrong")
    # I don't care. You figure it out.

try:
    with open("data.json", "rt") as r:
        new_count = json.load(r)["count"] + 1
except FileNotFoundError:
    print("File is missing.")
except PermissionError:
    print("File not readable.")
except json.decoder.JSONDecoderError:
    print("File is not valid JSON.")
except KeyError:
    print("Cannot find count.")
except TypeError:
    print("Count is not a number.")

如果你正在创建一个库,你可以在适当的地方使用预定义的异常类——但有时你需要传达 Python 创建者从未想过的错误,或者你需要比现有的异常做更精细的区分。这是您创建自定义异常的时候。

例如,Django 将定义django.contrib.auth.models.User.DoesNotExist异常来传达代码试图User在数据库中查找 a,但找不到User匹配给定条件的信息。能够捕捉到django.contrib.auth.models.User.DoesNotExist就像是一名医生,并且让一个病人不仅告诉你什么伤害了,而且带来了 X 光片和打印的家族史。


推荐阅读