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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("`Raising Exceptions`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/variables_data_types -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/strings -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/type_conversion -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/conditional_statements -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/for_loops -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/list_comprehensions -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/lists -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/tuples -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/dictionaries -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/sets -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/function_definition -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/importing_modules -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/using_packages -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/standard_libraries -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/classes_objects -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/encapsulation -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/raising_exceptions -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/data_collections -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/python_shell -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} python/build_in_functions -.-> lab-132723{{"`Defining Custom Python Exceptions`"}} end

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
>>>

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