Get startedGet started for free

Exceptions

1. Exceptions

Let's talk about exceptions. We'll start with a brief recap, and then learn how to define custom exceptions.

2. Errors are exceptions

Some statements in Python will cause an error when executed, for example, dividing by zero, combining objects of incompatible types, and many others. These errors are called exceptions. Many exceptions have special names, like ZeroDivisionError or TypeError, which you can see here. If exceptions are not handled correctly, they will stop the execution of our program. This often makes sense, for example, if we're trying to use a variable that was never defined, something must have gone very wrong with our script. But other times, it's undesirable.

3. Exception handling

For example, we might want to run the rest of the script but log the error without terminating the program. We can implement a special code to handle this case. We can use a try-except-finally sequence to catch an exception and handle it. Start with try, then place the code we're worried won't work inside. Let's demonstrate this with code we know will cause an error. Here, we try to add 5 and the string "a". Then, we add an except block, stating the name of the particular exception we want to handle, in this case a TypeError. Inside the except block, we provide the code that should be executed if this exception is raised, showing a print statement. Then, if this particular exception does happen, the program will not terminate but execute the code in the except block instead. We can also have multiple exception blocks. Lastly, we can use the optional "finally" block that will contain the code that runs no matter what.

4. Exception handling output

The output shows our print statement because the error was raised, but also includes the output from the finally block, which runs regardless.

5. Raising exceptions

Sometimes, we want to raise exceptions ourselves, for example when some conditions aren't satisfied. We can use the raise keyword followed by the exception to raise, optionally adding a specific error message in parentheses. The user of the code can then decide to handle the error using try/except.

6. Exceptions are classes

In Python, exceptions are actually classes inherited from built-in classes BaseException or Exception. Here's a glimpse into the huge built-in exception class hierarchy. For example, there's a general class of arithmetic errors, of which ZeroDivisionError is a subclass.

7. Custom exceptions

We can define our own exceptions in Python! Custom exception classes are useful because they can be specific to our application and provide bespoke error handling. To define a custom exception, we define a class that inherits from the built-in Exception class or one of its subclasses. The class itself can be empty because inheritance alone is enough to ensure that Python treats this class as an Exception. For example, we define a BalanceError class that inherits from Exception. Then, in our customer class, we raise a BalanceError exception if a negative balance value is passed on to the constructor.

8. Exception in constructor

If we attempt to create a customer with a negative account balance, the BalanceError exception is raised. Previously, we dealt with this situation by merely printing a message and then creating an object with zero balance.

9. Exceptions terminate the program

Handling it with exceptions is better, because in this case, the constructor terminates, and the customer object is not created at all, instead of being implicitly created with account balance set to zero, despite the error. This sends a clear signal to the user of the Customer class that something went wrong. The user, on their side,

10. Catching custom exceptions

can decide to handle this exception using try-except block if they want, but we, the authors of the code, do not make this decision for them. For example, here, the BalanceError is caught in the except block, and if that occurs, a customer is created with a zero balance instead.

11. Let's practice!

In the exercises, you'll explore creating and handling hierarchies of custom exceptions. Enjoy!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.