Files
coding-mentor-agent/kb/python-course-kb-practical-python/wiki/exercises/4-11-defining-a-custom-exception.md
T

1.5 KiB

id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
id source_exercise_id title section source_path source_repo source_commit student_visible_solution has_private_solution skip
practical-python-4.11 4.11 Defining a custom exception 4.4 Defining Exceptions 04_Classes_objects/04_Defining_exceptions.md https://github.com/dabeaz-course/practical-python 93dca856b41c61a0a0f85ae334116e4c125629ea false false false

Exercise 4.11: Defining a custom exception

Source: Practical Python Programming, 04_Classes_objects/04_Defining_exceptions.md.

Exercise 4.11: Defining a custom exception

It is often good practice for libraries to define their own exceptions.

This makes it easier to distinguish between Python exceptions raised in response to common programming errors versus exceptions intentionally raised by a library to a signal a specific usage problem.

Modify the create_formatter() function from the last exercise so that it raises a custom FormatError exception when the user provides a bad format name.

For example:

>>> from tableformat import create_formatter
>>> formatter = create_formatter('xls')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tableformat.py", line 71, in create_formatter
    raise FormatError('Unknown table format %s' % name)
FormatError: Unknown table format xls
>>>

Contents | Previous (4.3 Special methods) | Next (5 Object Model)

关联来源