Defining our own exceptions

Occasionally, when we want to raise an exception, we find that none of the built-in exceptions are suitable. 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. We don't even have to add any content to the class! We can, of course, extend BaseException directly, but I have never encountered a use case where this would make sense.

Here's a simple exception we might use in a banking application:

class InvalidWithdrawal(Exception): pass raise InvalidWithdrawal("You don't have $50 in your account") ...

Get Python 3 Object-Oriented Programming. - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.