Handling Errors Gracefully in Python

Cartoon robot pig types “hello” into a computer, which displays an error message. Pale orange background with “Python Exceptions” text.

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:

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, and 5.
  • 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:

This way, you can give clear feedback to the user.

Try this:

  • Enter hello and watch the ValueError message.
  • Enter 0 and see the ZeroDivisionError.
  • Enter 2 to 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:

  • else runs only if everything worked fine.
  • finally always runs, whether there was an error or not – handy for clean-up tasks.

Try this:

  • Experiment with valid and invalid inputs.
  • Notice how finally always 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.

Main Topic

Introducing Python Exceptions

Flat illustration of a train diverted from a broken bridge by someone pulling a lever, symbolising Python Exceptions safety handling.

This tutorial introduces Python exceptions, explaining what they are, why they matter, and how handling them prevents program crashes.