Search⌘ K
AI Features

try, except, or else!

Explore how to handle exceptions in Python using try, except, and else statements. Understand how the else clause runs only when no errors occur, and learn when and how to apply finally statements. This lesson equips you to write error-resistant code that handles exceptions gracefully.

We'll cover the following...

The try/except statement also has an else clause. The else will only run if there are no errors raised. We will spend a few moments looking at a couple examples:

Python 3.5
my_dict = {"a":1, "b":2, "c":3}
try:
value = my_dict["a"]
except KeyError:
print("A KeyError occurred!")
else:
print("No error occurred!")

Here we have a dictionary with 3 elements and in the ...