简介
用户定义的异常是通过类来定义的。
class NetworkError(Exception):
pass
异常总是继承自 Exception。
通常它们是空类。在类体中使用 pass。
你也可以创建异常层次结构。
class AuthenticationError(NetworkError):
pass
class ProtocolError(NetworkError):
pass
练习 4.11:定义自定义异常
对于库来说,定义自己的异常通常是个好习惯。
这样做便于区分因常见编程错误而引发的 Python 异常,与库为了表明特定使用问题而故意引发的异常。
修改上一个练习中的 create_formatter() 函数,使其在用户提供错误的格式名称时引发自定义的 FormatError 异常。
例如:
>>> from tableformat import create_formatter
>>> formatter = create_formatter('xls')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tableformat.py", line 80, in create_formatter
raise FormatError(f"Unknown table format {name}")
tableformat.FormatError: Unknown table format xls
>>>
总结
恭喜你!你已经完成了“定义异常”实验。你可以在 LabEx 中练习更多实验来提升你的技能。