python - 子类化异常有什么帮助?
问题描述
我没有直接调用异常,而是看到它被子类化,其中没有任何内容或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
在数据库中查找 a,但找不到User
匹配给定条件的信息。能够捕捉到django.contrib.auth.models.User.DoesNotExist
就像是一名医生,并且让一个病人不仅告诉你什么伤害了,而且带来了 X 光片和打印的家族史。
推荐阅读
- ios - 如何从 Swift 的扩展中排除特定的 UIButton?
- spring-data-jpa - 如何有条件地组合 JPA 查询的谓词?
- github-pages - 图片文件夹未从 Github repo 加载到 Github Pages
- swift - 背景图像在 Swift 中没有改变
- arrays - 无法修改我的数组 - 无法对不可变值使用变异成员:函数调用返回不可变值
- python - 通过添加多个列在 Pandas 数据框中创建一个新列
- simulation - 如何将同一队列中的不同代理类型优先分配给不同的车辆?
- entity-framework - System.Data.Entity.Infrastructure.DbUpdateException(重复表名并显示不存在)
- node.js - 尽管在 nodejs api 中使用了 cors 中间件,但 CORS 错误
- java - 编辑 aab 文件?