Alexa Metrics

Python series: exceptions in Python

Image of icons showing different Exceptions in Python

This article continues to discuss concepts pertaining to the Python language. Each article dives deeper to cover increasingly advanced concepts.

Today, we will discuss exceptions in Python. Exception handling is a method of testing your code against errors and trying to handle these errors.

We will use the try-except block in Python. This assembly consists of two blocks of code. First is the try block of code, which tests your code for errors. Next comes the except block of code, which handles the errors that arise.

There is also a final block, which lets you run your code regardless the outcome of the try-except block. The finally block is like a master switch to the code you have written.

Exception handling

When an error occurs in Python, an error message will display to tell you what has gone wrong. This will help you to handle these exceptions using the try statement, which is an underlying block of code that generates the exception. For example, the code below has a variable x that wasn’t defined. This causes an error.




print("An exception occurred")

In this case, when the code under the try statement is executed it results in an error. The code below the except statement will be executed to address the error. If this code wasn’t there, the program would have crashed without giving you the custom error.

There’s no limit to the number of exceptions. You can define as many as you want or think may be relevant to your coding paradigm.

Multiple errors

What can you do if want to customize error messages? Let’s say, for example, that we want one error message for each of the errors below. We want a custom message for a NameError error and another for a generic error. You could do this with the following code:



except NameError:

print("Variable x is not defined")


print("Something else went wrong")

The same can be achieved using the else keyword:




print("Something went wrong")


print("Nothing went wrong")


What about the master switch, which we know as the final statement? This statement doesn’t stop for exceptions and continues executing the program anyway:




print("Something went wrong")


print("The 'try except' is finished")

Are you interested yet? Start learning now with RoboGarden. Register today for free.

Python Series Intermediate python


Start Python coding

Let's start python coding with RoboGarden learning journey.

Canada Flag Privacy Policy Terms of Use
Got an invite