How to Handle Errors and Exceptions in Python Like a Pro

Learning Python for Beginners — Part 7

By Data Impala

Welcome back to another lesson in our Data Impala: Learning Python for Beginners series! 

In the previous lesson, we explored how to read and write files using Python

Now, it’s time to level up by learning how to handle errors and exceptions. 

This is one of the most important parts of writing reliable code—because things will go wrong, and your job as a programmer is to make sure your code can recover gracefully.

Why Do We Need Error Handling?

Imagine you wrote a program to read a file, and it crashes just because the file isn’t there. 

That’s not user-friendly. 

Even worse, if you’re writing code for others to use, you don’t want one small mistake to bring everything to a halt.

Instead, we can catch and manage these errors, so our program keeps running or at least fails with a clear message.

Types of Errors in Python

Python generally throws two types of issues:

  • Syntax Errors – Mistakes in the code structure
  • Exceptions – Errors that happen during execution

1. Syntax Errors

These are mistakes in how the code is written. For example:

if x == 5
    print("x is 5")

Here, the missing colon after if x == 5 will raise a SyntaxError.

2. Exceptions

These happen while the code is running.

print(10 / 0)

This raises a ZeroDivisionError because you can’t divide by zero.

The try-except Block

The most basic way to catch errors in Python is with try and except.

try:
    # Code that might cause an error
    x = 10 / 0
except ZeroDivisionError:
    # Code that runs if an error happens
    print("You can't divide by zero!")

What’s Happening:

  • The code inside try runs first.
  • If an error happens, Python looks for a matching except block.
  • If it finds one, it runs that block instead of crashing.

Catching Different Errors

You can catch specific types of errors using their names:

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")

This helps you give more helpful feedback depending on the error.

Sometimes, you may want to catch any error:

try:
    risky_code()
except Exception as e:
    print("Something went wrong:", e)

This will catch any exception, print the error, and let your program continue. But don’t overuse it—catch specific exceptions whenever possible.

else and finally Blocks

Python also lets you add else and finally blocks:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error: can't divide by zero")
else:
    print("Everything went fine! Result:", result)
finally:
    print("This always runs, error or not.")

Breakdown:

else: Runs if no error happened.

finally: Runs no matter what, useful for cleanup tasks.

Raising Your Own Errors

You can trigger errors using raise:

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    print("Age is set to", age)

This is helpful when you want to stop the program if the user input is invalid.

Real Example: Safer File Handling

In the last lesson, you learned how to work with files. Let’s combine that with error handling:

filename = input("Enter filename: ")

try:
    with open(filename, "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("Sorry, the file doesn't exist.")
except PermissionError:
    print("You don't have permission to open this file.")
except Exception as e:
    print("An unexpected error occurred:", e)

This script is more robust and won’t crash even if the file is missing or unreadable.

Practice Exercise: Error-Handled Calculator

Write a small calculator program that:

  • Takes two numbers as input
  • Takes a math operation: +, -, *, or /
  • Performs the calculation
  • Handles these errors:
  1.  Invalid number input
  2.  Invalid operation input
  3.  Division by zero

Sample Code Skeleton:

try:
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    op = input("Choose operation (+, -, *, /): ")

    if op == "+":
        print(num1 + num2)
    elif op == "-":
        print(num1 - num2)
    elif op == "*":
        print(num1 * num2)
    elif op == "/":
        print(num1 / num2)
    else:
        print("Invalid operation")

except ValueError:
    print("Please enter valid numbers.")
except ZeroDivisionError:
    print("You can't divide by zero.")

Key Takeaways

  • try and except let you control what happens when something goes wrong.
  • Use specific exception names when possible.
  • else runs only if there’s no error.
  • finally always runs, great for cleanup.
  • Use raise to create your own errors.
  • Learning to handle errors means your code is safer, more professional, and easier for others to use.

Next Up

In our next lesson, we’ll learn how to work with modules and packages in Python—how to organize your code and use tools built by others.

Until then, keep coding, keep failing safely, and keep learning—only on Data Impala!

✍️ Written by Ahnaf Chowdhury

📘 Series: Learning Python for Beginners — Part 7

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top