← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Python Error Handling

python Python 2.0+ Intermediate

Also Known As

try/except exception handling Python exceptions

TL;DR

Python uses try/except/else/finally blocks and a rich exception hierarchy — good error handling is specific, informative, and never silently swallows exceptions.

Explanation

Python exceptions are objects in a hierarchy (BaseException > Exception > specific types). Best practices: catch the most specific exception possible, not bare except or except Exception. The else clause runs when no exception was raised — useful for code that should only run on success. finally always runs — use it for cleanup. Custom exceptions should inherit from Exception, not BaseException. Use raise from to preserve exception chains.

Common Misconception

Broad exception catching is safe — catching all exceptions hides bugs, makes debugging impossible, and swallows keyboard interrupts and memory errors.

Why It Matters

Silent exception swallowing is one of the most common sources of mysterious Python bugs — a function that silently returns None when it should raise tells the caller nothing went wrong.

Common Mistakes

  • Bare except: clause — catches everything including SystemExit and KeyboardInterrupt; always specify the exception type.
  • Using pass in an except block — silently swallows the error with no logging or handling.
  • Not using raise from to preserve the original exception context: raise NewException(...) from original_exc.
  • Catching broad Exception when a specific type is known — makes error messages less informative and hides unrelated bugs.

Code Examples

✗ Vulnerable
# Silent exception swallowing — hides all errors:
def get_user(user_id):
    try:
        return db.fetch(user_id)
    except:  # Catches EVERYTHING including KeyboardInterrupt
        pass  # Returns None silently — caller has no idea what went wrong
✓ Fixed
# Specific exception handling with context:
class UserNotFoundError(ValueError):
    def __init__(self, user_id):
        super().__init__(f'User {user_id} not found')
        self.user_id = user_id

def get_user(user_id: int) -> User:
    try:
        return db.fetch(user_id)
    except DatabaseConnectionError as e:
        raise RuntimeError('Database unavailable') from e  # Preserve chain
    except RecordNotFoundError:
        raise UserNotFoundError(user_id)  # Domain-specific exception
    # No finally needed here — let other exceptions propagate

Added 15 Mar 2026
Edited 22 Mar 2026
Views 27
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping W 0 pings T 2 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 2 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 2 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 8 Perplexity 6 Unknown AI 3 Ahrefs 2 Google 2 ChatGPT 1
crawler 22
DEV INTEL Tools & Severity
🟠 High ⚙ Fix effort: Low
⚡ Quick Fix
Catch specific exceptions, never bare except: — bare except catches SystemExit and KeyboardInterrupt preventing clean shutdown; use except Exception as e: at minimum
📦 Applies To
python 2.0 web cli
🔗 Prerequisites
🔍 Detection Hints
bare except: without exception type; catching Exception silently; no logging in except block; using exceptions for control flow
Auto-detectable: ✓ Yes pylint ruff flake8 mypy
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Medium Context: Function Tests: Update
CWE-390 CWE-755

✓ schema.org compliant