Python - 23

Python - 23: Error Handling With Try & Except

try and except let your program handle certain errors without stopping completely.

Your challenge: Test how Python handles invalid number input and a division-by-zero error, then change the messages.

✦ Python Editor
▶ Output

Use try for risky code

Code that might fail goes inside a try block.

For example, int(input(...)) can fail if the user enters text instead of a number.

Catch the error with except

If that error happens, Python skips the rest of the try block and runs the matching except block.

For invalid number conversion, use: except ValueError:

Catch specific errors

Dividing by zero causes a ZeroDivisionError, so it can be handled with: except ZeroDivisionError:

Try it: Enter both a valid number and some text. Then change the two error messages.

Good Python habit: Catch specific errors when you know what might go wrong instead of using a plain except for everything.

👀 Show Example Solution
try:
    number = int(input("Enter a number: "))

    print("You entered:")
    print(number)

except ValueError:
    print("Please enter numbers only!")

try:
    answer = 10 / 0
    print(answer)

except ZeroDivisionError:
    print("Math error: cannot divide by zero!")

The starter now runs correctly before the learner changes anything, while still giving them something simple to experiment with.