100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Python Exception Handling Cheat Sheet

Python Exception Handling Cheat Sheet

Python error handling covering try/except/else/finally, catching multiple exceptions, raising and chaining errors, and custom exceptions.

1 PageBeginnerApr 12, 2026

try / except / else / finally

The full structure of Python's exception handling block.

python
try:    result = 10 / 0except ZeroDivisionError as e:    print(f"Error: {e}")else:    print("No error occurred")   # runs only if try succeededfinally:    print("Always runs")          # runs no matter what

Catching Multiple Exceptions

Handling several exception types with one or more except clauses.

python
try:    value = int(input("Enter a number: "))except (ValueError, TypeError) as e:    print(f"Invalid input: {e}")except Exception as e:    print(f"Unexpected error: {e}")  # broad fallback, keep specific

Raising & Chaining Exceptions

Raising your own errors and preserving the original cause.

python
def validate_age(age):    if age < 0:        raise ValueError("Age cannot be negative")    return agetry:    validate_age(-5)except ValueError as e:    raise RuntimeError("Validation failed") from e  # preserves e as __cause__

Custom Exception Classes

Defining domain-specific exceptions by subclassing Exception.

python
class InsufficientFundsError(Exception):    def __init__(self, balance, amount):        self.balance = balance        self.amount = amount        super().__init__(f"Cannot withdraw {amount}, balance is {balance}")def withdraw(balance, amount):    if amount > balance:        raise InsufficientFundsError(balance, amount)    return balance - amount

Common Built-in Exceptions

Frequently encountered exception types in the standard library.

  • ValueError- correct type but inappropriate value, e.g. int('abc')
  • TypeError- operation applied to an object of an inappropriate type
  • KeyError- dictionary key not found
  • IndexError- sequence index out of range
  • AttributeError- attribute reference or assignment fails
  • FileNotFoundError- file or directory does not exist
  • ZeroDivisionError- division or modulo by zero
  • StopIteration- raised by next() when an iterator is exhausted
Pro Tip

Never write a bare `except:` clause — it catches everything including KeyboardInterrupt and SystemExit, making your program hard to stop and hiding real bugs. Catch specific exception types, or at most `except Exception:`.

Was this cheat sheet helpful?

Explore Topics

#PythonExceptionHandling#PythonExceptionHandlingCheatSheet#Programming#Beginner#Try#Except#Else#Finally#ErrorHandling#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet