PythonMastery

try except example in Python

Divide two numbers typed by the user. Catch ZeroDivisionError and ValueError separately, so each mistake gets its own clear message.

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

python
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.

output
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

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:

python
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}")
output
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.

Learn the idea: Errors & Exceptions: When Things Go Wrong