Error Handling in Python – Dealing with Exceptions Gracefully

Errors are inevitable in programming, but Python provides powerful tools to handle them gracefully. Good error handling makes your programs more robust and user-friendly.

Understanding Exceptions

When Python encounters an error, it raises an exception. Without proper handling, exceptions cause your program to crash:

# This will cause a ZeroDivisionError
result = 10 / 0  # Program crashes here

Basic Try-Except

Use try-except blocks to catch and handle exceptions:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
    result = 0

Handling Multiple Exceptions

Catch different types of errors with multiple except blocks:

def safe_divide(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        print("Error: Cannot divide by zero")
        return None
    except TypeError:
        print("Error: Please provide numbers only")
        return None

print(safe_divide(10, 2))    # 5.0
print(safe_divide(10, 0))    # Error message, returns None
print(safe_divide(10, "2"))  # Error message, returns None

Generic Exception Handling

Catch any exception with a general except block:

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    result = 100 / number
    print(f"Result: {result}")
except Exception as e:
    print(f"An error occurred: {e}")

Finally Block

Code in the finally block always runs, whether an exception occurs or not:

try:
    file = open("data.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    # This always runs
    if 'file' in locals():
        file.close()
    print("Cleanup completed")

Raising Custom Exceptions

Use the raise keyword to trigger exceptions intentionally:

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age seems unrealistic")
    return True

try:
    validate_age(-5)
except ValueError as e:
    print(f"Validation error: {e}")

Common Exception Types

  • ValueError: Invalid value for operation
  • TypeError: Wrong data type
  • KeyError: Dictionary key not found
  • IndexError: List index out of range
  • FileNotFoundError: File doesn’t exist

Best Practices

# Be specific with exceptions
try:
    # risky code
    pass
except FileNotFoundError:
    # handle file errors
    pass
except PermissionError:
    # handle permission errors
    pass

# Don't catch all exceptions unless necessary
# try:
#     # code
# except:  # Too broad - avoid this
#     pass

Proper error handling makes your programs more professional and helps users understand what went wrong and how to fix it.

Author

  • Mohammad Golam Dostogir, Software Engineer specializing in Python, Django, and AI solutions. Active contributor to open-source projects and tech communities, with experience delivering applications for global companies.
    GitHub

    View all posts
Index