Defining Our Own Exceptions
Learn how we can create our own exceptions in Python.
Overview
Occasionally, when we want to raise an exception, we find that none of the built-in exceptions are suitable. The distinction is often focused on how applications must handle the exception; when we introduce a new exception, it must be because there will be distinct processing in a handler.
There’s no good reason to define an exception that’s handled exactly like ValueError
; we can use ValueError
. Luckily, it’s trivial to define new exceptions of our own. The name of the class is usually designed to communicate what went wrong, and we can provide arbitrary arguments in the initializer to include additional information.
All we have to do is inherit from the Exception
class or one of the existing exceptions that’s semantically similar. We don’t even have to add any content to the class. We can, of course, extend BaseException
directly, but this means we’re inventing new ways of stopping a running program, a very unusual thing to be creating.
Banking example
Here’s a simple exception we might use in a banking application:
Get hands-on with 1400+ tech skills courses.