My Universe

Mens Insana in Corpore Ignavo

Elegant Python Exceptions

2023-10-31 Python

Particularly when creating library packages in Python, raising exceptions is a great way to let the downstream developer know about problems occuring while executing code from within the library. Python’s built-in exceptions cover a whole host of cases. However, some problems might be library-specific and deserve a custom exception.

Custom Exceptions

Creating a custom exception in Python isn’t particularly hard when observing a few rules:

  • Custom exceptions shall be derived from Python’s Exception class
  • By convention, exception names shall end with “Error”
1class MyLibError(Exception):
2    pass

In many library packages, you will find exceptions similar to the one shown in the code example above. There’s nothing wrong with that; if chosen wisely, the exception name by itself will already tell what went wrong. However, the more details an exception provides about the circumstances it was raised in, the easier to diagnose and debug the problem, and the more appropriate the reaction to an exception.

Continue reading