gpt4 book ai didi

python - 对异常进行子类化有何帮助?

转载 作者:行者123 更新时间:2023-12-05 09:11:09 25 4
gpt4 key购买 nike

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

class ACustomException(Exception):
pass

class BCustomException(Exception):
pass

最佳答案

引发 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,但找不到符合给定条件的 User。能够捕捉到 django.contrib.auth.models.User.DoesNotExist 就像是一名医生,得到的病人不仅会告诉你哪里疼,还会带来 X 光片和打印的家族病史和他们在一起。

关于python - 对异常进行子类化有何帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60425503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com