10 Errors and exceptions
Any changes you make to the code on this page, including your solutions to exercises, are temporary. If you leave or reload the page, all changes will be lost. If you would like to keep your work, copy and paste your code into a separate file or editor where it can be saved permanently.
10.1 Syntax errors
A syntax error means code does not follow the language rules (the syntax). If we try to run such code, Python stops immediately and shows an error message.
For example, the following code is not syntactically correct because of a missing colon after the if condition:
Another very common syntax error is incorrect indentation:
10.2 Runtime exceptions
If code is syntactically correct, Python starts executing it. If the code tries to do something that is not allowed, Python raises an exception, which by default stops the program and shows an error message.
We have already seen multiple types of exceptions, for example:
We can change the default behavior using a try-except block:
try:
# Code to execute
except:
# Code executed only if an exception is raised in the `try` blockIf no exception occurs, Python simply skips the except block. However, if an exception does occur, Python stops the rest of the try block and runs the except block to handle the error:
Exercise: Try changing string to a value like "42" to see the difference.
To handle only a specific type of exceptions, we can specify the type after except:
We can use multiple except blocks to handle different types:
try:
# Code
except IndexError:
# Handling of an IndexError
except KeyError:
# Handling of a KeyErrorWe can also handle multiple types in the same except block by listing them in a tuple:
try:
# Code
except (IndexError, KeyError):
# Handling of either an IndexError or a KeyErrorTo store (information about) an exception in a variable, we can use as:
Since we use the value variable after the try-except block, we need to make sure it exists even if an exception occurs. One way is to set the variable inside the except block, as shown above. An even better approach is to initialize it before the try block:
If we want to handle any exception and store it, we can use Exception as the type:
We can also include a finally block, which always runs, whether or not an exception occurred. This is useful for cleanup tasks, such as closing files or releasing resources:
Exercise. Instead of int(string) try 1 / 0 (this raises a ZeroDivisionError, which is not handled by the program). Run the program and check the execution step by step — which parts of the code were executed and which were not?
Exercise. Write two functions, input_int and input_float, which ask the user for an integer and a float, respectively. The functions should repeatedly ask for input until the user enters a valid number. Each function takes a prompt as a parameter and returns the entered value as an int or float.
On the book’s website, due to limitations with user input, input() has been changed to return a random string, integer, or float instead of prompting the user.
Hint Use an infinite loop (while True:) to keep asking until we get a valid input.
Sample solution
def input_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
pass
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
number = input_int("What's your favorite integer? ")
print(f'You entered {number}.')
number = input_float("And what's your favorite float? ")
print(f'You entered {number}.')