Editor settings

General settings

Save settings

Learn to program with Python

Handle an error with try except #

In Python, when an error occurs during the execution of a program, it can cause the program to terminate and stop running. However, by using the try and except block, you can catch and handle these errors instead of having your program stop working.

For example, when the code below is executed, we will get the ZeroDivisionError from the first line of code, because you cannot divide any number by zero in Python. And the function print() in the second line will not be executed.

10 / 0
print("The program is running")
# Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    10 / 0
ZeroDivisionError: division by zero

To handle the error above, we can use the try except block, like so:

try:
    10 / 0
except:
    print("Error: Cannot divide the number by zero")
print("The program is running")

In the example above, we wrap the code that might cause an error within the try block. If an error occurs inside the try block, the code inside the except block will execute.

Here's the output of the example above. We can see that the print() inside the except block is run, and the program continues to run and execute the last print() function:

# Output
Error: Cannot divide the number by zero
The program is running

Exercise #

  • Update the body of the function divide_the_numer() to handle an error.

Tests #

  • divide_the_number(4, 2) should return 2.0
  • divide_the_number(10, 4) should return 2.5
  • divide_the_number(10, 0) should print the message "You cannot divide by zero!"
  • Must use try and except in the function
Output will be displayed here