Skip to content
5 min read

Python Error Handling: try, except, and When to Use Each

Master Python error handling with try, except, else, and finally. Learn how to catch specific exceptions, write clean error messages, and avoid common beginner mistakes.

#python #beginner #bestpractices

Errors happen in every program. The difference between a beginner and an experienced developer isn’t that they write bug-free code — it’s that they handle errors gracefully. Python error handling with try and except lets your program respond to problems instead of crashing.

The Basics: try and except

Wrap code that might fail in a try block. If an error occurs, Python jumps to the except block instead of crashing:

try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print(f"Result: {result}")
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("That's not a valid number.")

Always catch specific exceptions. Catching bare except: (or except Exception:) hides bugs and makes debugging harder.

The else and finally Clauses

Python’s try block has two optional extras that beginners often miss:

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found.")
else:
    # Runs only if NO exception occurred
    print(f"File loaded: {len(content)} characters")
finally:
    # Runs ALWAYS — perfect for cleanup
    print("Done.")
  • else — runs when the try block succeeds with no errors
  • finally — runs regardless of what happened, great for closing files or database connections

Raising Your Own Exceptions

You can raise exceptions intentionally to signal that something went wrong in your code:

def get_user_age(age):
    if age < 0:
        raise ValueError(f"Age cannot be negative: {age}")
    return age

try:
    get_user_age(-5)
except ValueError as e:
    print(f"Invalid input: {e}")

Using as e gives you access to the error message. For larger projects, create custom exception classes that inherit from Exception — it makes your error types meaningful and easy to catch specifically.

Conclusion

Good Python error handling is what separates code that works in demos from code that works in production. Use try/except for anything that can fail — file reads, network requests, user input, database queries. Catch specific exceptions, use finally for cleanup, and raise exceptions when your own validation fails.

Read next: Working with JSON in Python: A Practical Guide

External resource: Python Docs — Errors and Exceptions

Kaikobud Sarkar

Kaikobud Sarkar

Software engineer passionate about backend technologies and continuous learning. I write about Python frameworks, cloud architecture, engineering growth, and staying current in tech.

Related Articles

How to Write Clean Functions in JavaScript

Learn how to write clean JavaScript functions that are easy to read, test, and maintain. This guide covers naming, single responsibility, pure functions, and avoiding common pitfalls.

#javascript #bestpractices

CSS Flexbox in Plain English: A Beginner's Guide

Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.

#css #flexbox