子类化异常有什么帮助?

nis*_*ish 2 python inheritance exception

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

class ACustomException(Exception):
    pass

class BCustomException(Exception):
    pass
Run Code Online (Sandbox Code Playgroud)

Ama*_*dan 5

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

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

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

如果您正在创建一个库,则可以在适当的情况下使用预定义的异常类 \xe2\x80\x94,但有时您需要传达 Python 创建者从未考虑过的错误,或者需要比现有异常进行更精细的区分。这是您创建自定义异常的时候。

\n\n

例如,Django 将定义异常来传达代码尝试在数据库中django.contrib.auth.models.User.DoesNotExist查找,但找不到与给定条件匹配的情况。能够发现疾病就像是一名医生,接诊的病人不仅会告诉你疼痛情况,还会带来 X 光片和打印的家族史。UserUserdjango.contrib.auth.models.User.DoesNotExist

\n