Defining Custom Python Exceptions

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

User defined exceptions are defined by classes.

class NetworkError(Exception):
    pass

Exceptions always inherit from Exception.

Usually they are empty classes. Use pass for the body.

You can also make a hierarchy of your exceptions.

class AuthenticationError(NetworkError):
     pass

class ProtocolError(NetworkError):
    pass

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 80, in create_formatter
    raise FormatError(f"Unknown table format {name}")
tableformat.FormatError: Unknown table format xls
>>>
âœĻ Check Solution and Practice

Summary

Congratulations! You have completed the Defining Exceptions lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like