Python Exception Handling Explained with Real Examples

What Is Exception Handling?

When Python encounters an error during execution, it raises an exception. Without handling, your entire program crashes. Exception handling lets you catch those errors and respond gracefully instead.

Think of it like a safety net: your code tries something risky, and if it fails, the safety net catches the problem instead of letting the whole program fall.

Basic try/except Syntax

The core pattern is simple: put risky code inside try, and handle errors in except.

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

Notice we’re catching specific exception types. This is a best practice — never catch a bare Exception unless you have a good reason.

The finally Block

Code inside finally always runs, whether or not an exception occurred. Use it to release resources like files or database connections.

try:
    f = open("data.txt", "r")
    content = f.read()
    print(content)
except FileNotFoundError:
    print("The file doesn't exist.")
finally:
    f.close()  # Always closes, even if an exception occurred
    print("File closed.")

Raising Custom Exceptions

You can create your own exception classes by inheriting from Exception. This makes your error messages much clearer in real applications.

class AgeError(Exception):
    """Raised when an invalid age is provided."""
    pass

def set_age(age):
    if age < 0 or age > 150:
        raise AgeError(f"Invalid age: {age}. Must be between 0 and 150.")
    return age

try:
    set_age(200)
except AgeError as e:
    print(f"Caught custom error: {e}")

Common Mistakes to Avoid

Catching too broadly: except Exception swallows all errors including bugs you’d want to know about. Always be specific.

Silent failures: An empty except block hides problems. At minimum, log the error: except ValueError as e: print(e).

Overusing exceptions for control flow: Don’t use try/except instead of an if check when an if check is simpler and clearer.

Quick Reference

try:
    # Code that might raise an exception
    risky_operation()
except SpecificError as e:
    # Handle specific error, 'e' has the error message
    print(e)
except (TypeError, ValueError):
    # Handle multiple types with a tuple
    print("Type or value problem")
else:
    # Runs only if NO exception occurred
    print("Success!")
finally:
    # Always runs
    cleanup()

Exception handling is one of those skills that separates beginner code from professional code. Start with specific exceptions, use finally for cleanup, and create custom exceptions when your domain needs them.

Recommended Tool

Write Python 10x Faster with AI

GitHub Copilot suggests entire functions as you type. Used by 1M+ developers.

Try Free for 30 Days →

Similar Posts

Leave a Reply

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