Mistakes happen – both in life and in code. Luckily, Python gives us tools to stop our programs crashing every time something unexpected happens. The main tool is the try...except block. Let’s explore what it is, why it’s useful, and how you can use it.
Why Use try...except?
Without exception handling, your program will simply stop running when it hits an error. Imagine a cash machine that shuts down the moment someone types the wrong PIN – not very helpful! By using try...except, you can catch errors and decide what to do next, instead of letting your program collapse.
Example:
print("Let's divide some numbers!")
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except:
print("Oops! Something went wrong.")
Here, if the user types 0 or something that isn’t a number, Python won’t crash – it will politely print the error message.
Try this:
- Run the code and type different inputs like
0,banana, and5. - See how Python responds each time.
Catching Specific Exceptions
It’s better practice to catch specific errors, so you know exactly what went wrong.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ValueError:
print("That wasn’t a number!")
except ZeroDivisionError:
print("You can’t divide by zero!")
This way, you can give clear feedback to the user.
Try this:
- Enter
helloand watch theValueErrormessage. - Enter
0and see theZeroDivisionError. - Enter
2to get a proper result.
Adding a Safety Net with else and finally
Sometimes, you want extra steps depending on whether an error happened or not. That’s where else and finally come in.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)
else:
print("Great! The result is", result)
finally:
print("Thanks for using the divider program.")
elseruns only if everything worked fine.finallyalways runs, whether there was an error or not – handy for clean-up tasks.
Try this:
- Experiment with valid and invalid inputs.
- Notice how
finallyalways runs at the end.
Wrapping Up
The try...except block is like a safety net for your code. Instead of letting errors derail your program, you catch them, explain them, and keep things moving smoothly. With practice, you’ll learn when to use it, which errors to catch, and how to make your programs friendly even when things go wrong.

