What's the proper way to handle exceptions in Python without suppressing errors?

Answered
Aug 30, 2025 521 views 5 answers
16

I'm working on a Python application and running into an issue with Python debugging. Here's the problematic code:


# Current implementation
class DataProcessor:
    def __init__(self):
        self.data = []
    
    def process_large_file(self, filename):
        with open(filename, 'r') as f:
            self.data = f.readlines()  # Memory issue with large files
        return self.process_data()

The error message I'm getting is: "TypeError: unsupported operand type(s) for +: 'int' and 'str'"

What I've tried so far:

  • Used pdb debugger to step through the code
  • Added logging statements to trace execution
  • Checked Python documentation and PEPs
  • Tested with different Python versions
  • Reviewed similar issues on GitHub and Stack Overflow

Environment information:

  • Python version: 3.11.0
  • Operating system: macOS Ventura
  • Virtual environment: venv (activated)
  • Relevant packages: django, djangorestframework, celery, redis

Any insights or alternative approaches would be very helpful. Thanks!

L
Asked by lisa_data
Bronze 50 rep

Comments

joseph: I'm new to Django ORM optimization. Could you explain the database indexing part in simpler terms? 1 week, 4 days ago

alex_dev: This threading vs multiprocessing explanation cleared up my confusion. Saved me hours of debugging! 1 week, 4 days ago

5 Answers

17

Python decorators with arguments require a three-level nested function. Here's the proper implementation:

import functools

# Decorator with arguments
def retry(max_attempts=3, delay=1):
    def decorator(func):
        @functools.wraps(func)  # Preserves function metadata
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise e
                    time.sleep(delay)
        return wrapper
    return decorator

# Usage
@retry(max_attempts=5, delay=2)
def unreliable_function():
    # Function that might fail
    pass

Class-based decorator (alternative approach):

class Retry:
    def __init__(self, max_attempts=3, delay=1):
        self.max_attempts = max_attempts
        self.delay = delay
    
    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(self.max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == self.max_attempts - 1:
                        raise e
                    time.sleep(self.delay)
        return wrapper

# Usage
@Retry(max_attempts=5, delay=2)
def another_function():
    pass
J
Answered by james_ml 1 week, 4 days ago
Bronze 90 rep
29

This Django error typically occurs when you're trying to save a model instance that violates a unique constraint. Here's how to handle it properly:

from django.db import IntegrityError
from django.http import JsonResponse

try:
    user = User.objects.create(
        username=username,
        email=email
    )
except IntegrityError as e:
    if 'username' in str(e):
        return JsonResponse({'error': 'Username already exists'}, status=400)
    elif 'email' in str(e):
        return JsonResponse({'error': 'Email already exists'}, status=400)
    else:
        return JsonResponse({'error': 'Data integrity error'}, status=400)

Always use get_or_create() when you want to avoid duplicates:

user, created = User.objects.get_or_create(
    username=username,
    defaults={'email': email, 'first_name': first_name}
)
A
Answered by abadi 1 week, 4 days ago
Bronze 60 rep

Comments

azzani: Could you provide the requirements.txt for the packages used in this solution? 1 week, 4 days ago

sarah_tech: Perfect! This JWT authentication setup works flawlessly with my React frontend. 1 week, 4 days ago

26

Python decorators with arguments require a three-level nested function. Here's the proper implementation:

import functools

# Decorator with arguments
def retry(max_attempts=3, delay=1):
    def decorator(func):
        @functools.wraps(func)  # Preserves function metadata
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise e
                    time.sleep(delay)
        return wrapper
    return decorator

# Usage
@retry(max_attempts=5, delay=2)
def unreliable_function():
    # Function that might fail
    pass

Class-based decorator (alternative approach):

class Retry:
    def __init__(self, max_attempts=3, delay=1):
        self.max_attempts = max_attempts
        self.delay = delay
    
    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(self.max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == self.max_attempts - 1:
                        raise e
                    time.sleep(self.delay)
        return wrapper

# Usage
@Retry(max_attempts=5, delay=2)
def another_function():
    pass
W
Answered by william 1 week, 4 days ago
Newbie 40 rep

Comments

abaditaye: This Python memory optimization technique reduced my application's RAM usage by 60%. Brilliant! 1 week, 4 days ago

23

This Django error typically occurs when you're trying to save a model instance that violates a unique constraint. Here's how to handle it properly:

from django.db import IntegrityError
from django.http import JsonResponse

try:
    user = User.objects.create(
        username=username,
        email=email
    )
except IntegrityError as e:
    if 'username' in str(e):
        return JsonResponse({'error': 'Username already exists'}, status=400)
    elif 'email' in str(e):
        return JsonResponse({'error': 'Email already exists'}, status=400)
    else:
        return JsonResponse({'error': 'Data integrity error'}, status=400)

Always use get_or_create() when you want to avoid duplicates:

user, created = User.objects.get_or_create(
    username=username,
    defaults={'email': email, 'first_name': first_name}
)
J
Answered by john_doe 1 week, 4 days ago
Bronze 50 rep

Comments

abdullah: Great Python profiling example! The cProfile output helped me identify the bottleneck in my data processing pipeline. 1 week, 4 days ago

19

To optimize Django QuerySets and avoid N+1 problems, use select_related() for ForeignKey and OneToOneField, and prefetch_related() for ManyToManyField and reverse ForeignKey:

# Bad: N+1 query problem
for book in Book.objects.all():
    print(book.author.name)  # Each iteration hits the database

# Good: Use select_related for ForeignKey
for book in Book.objects.select_related('author'):
    print(book.author.name)  # Single query with JOIN

# Good: Use prefetch_related for ManyToMany
for book in Book.objects.prefetch_related('categories'):
    for category in book.categories.all():
        print(category.name)  # Optimized with separate query

You can also use only() to limit fields and defer() to exclude heavy fields:

# Only fetch specific fields
Book.objects.only('title', 'author__name').select_related('author')

# Defer heavy fields
Book.objects.defer('content', 'description')
A
Answered by abdullah 1 week, 4 days ago
Bronze 60 rep

Comments

james_ml: Perfect! This JWT authentication setup works flawlessly with my React frontend. 1 week, 4 days ago

Your Answer

You need to be logged in to answer questions.

Log In to Answer