try and except

Put code that might fail inside a try block. Below it, write an except block for the error you expect. If that error happens, the except block handles it, and the program keeps running.

total = 120
people = 0

try:
    print(total // people)
except ZeroDivisionError:
    print("Nobody to split the bill with")

print("Bill closed")

Output:

Nobody to split the bill with
Bill closed

Dividing by zero raises ZeroDivisionError. Python skips the rest of the try block and runs the matching except block. Then it carries on with the code after it, so Bill closed still prints.

Name the exception you expect, as this example does. A bare except:, with no name after it, catches every error. That includes your own mistakes, such as a misspelled variable name, and it hides them from you. Also keep the try block small, around just the code that might fail.

In the exercise, handle division by zero and print the final message.