创建自定义异常-python cookbook(第3版)高清中文完整版

时间:2024-06-29 23:06:52
【文件属性】:

文件名称:创建自定义异常-python cookbook(第3版)高清中文完整版

文件大小:4.84MB

文件格式:PDF

更新时间:2024-06-29 23:06:52

python cookbook 第3版 高清 中文完整版

14.8 创建自定义异常 问题 You’re building an application and would like to wrap lower-level exceptions with cus‐ tom ones that have more meaning in the context of your application. 解决方案 Creating new exceptions is easy—just define them as classes that inherit from Excep tion (or one of the other existing exception types if it makes more sense). For example, if you are writing code related to network programming, you might define some custom exceptions like this: class NetworkError(Exception): pass class HostnameError(NetworkError): pass class TimeoutError(NetworkError): pass class ProtocolError(NetworkError): pass Users could then use these exceptions in the normal way. For example: try: msg = s.recv() except TimeoutError as e: ...


网友评论