When Python cannot do something, it raises an exception and the program stops. A try/except block catches the exception so the program can print a helpful message and continue.
The program
def divide(): try: a = float(input("First number: ")) b = float(input("Second number: ")) print(f"{a} / {b} = {a / b}") except ValueError: print("That is not a number.") except ZeroDivisionError: print("You cannot divide by zero.") # run it three times to show all three results for _ in range(3): divide() print()
Typed in this example: 10, 4, 10, 0, ten. Press Run to type your own.
First number: 10 Second number: 4 10.0 / 4.0 = 2.5 First number: 10 Second number: 0 You cannot divide by zero. First number: ten That is not a number.
How it works
- Python runs the lines inside
tryone by one. If one of them raises an exception, the rest of thetryblock is skipped and Python looks for a matchingexcept. float("ten")raises aValueError. In the third run this happens on the first question, so the second question is never asked.10 / 0raises aZeroDivisionError.- Each
exceptnames one exception type, so each mistake gets its own message. An exception that matches noexcept(for example aKeyboardInterruptfrom Ctrl+C) is not caught, and it still stops the program.
Without the try, the program would stop with a traceback such as ZeroDivisionError: float division by zero.
One except for both, with the message
To handle several types the same way, put them in a tuple. as error gives you the exception object, and printing it shows Python's own message:
for a, b in [("8", "2"), ("8", "0"), ("8", "two")]: try: print(float(a) / float(b)) except (ValueError, ZeroDivisionError) as error: print(f"Error: {error}")
4.0 Error: float division by zero Error: could not convert string to float: 'two'
Avoid a bare except: with no type. It catches every error, including mistakes in your own code, and hides them. The input validation loop uses try/except to keep asking until the answer is valid.
Related programs: try except else finally.