Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 13

Python Exception Handling

5 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

An exception is an error detected at run time that interrupts normal flow.

Python lets you catch it with try/except/else/finally, raise your own, handle several types and rely on a rich hierarchy of built-in exceptions.

Real programs meet bad input, missing files and network failures; robust code handles them gracefully.

Input validation, file and network I/O, database transactions, APIs and long-running services.

1

Exception Handling in Python

Exception handling is the mechanism for responding to run-time errors without crashing. The try block holds risky code; except blocks handle specific exceptions; else runs only if no exception occurred; finally always runs. An unhandled exception prints a traceback and terminates the program.

In short: Try something risky. If it breaks, run the rescue plan instead of letting the whole program fall over.

Think about it

The full try/except/else/finally flow is the first thing examiners ask. A form handler catches ValueError for a bad age and shows a friendly message instead of a crash.

Syntax errors are found before execution; exceptions occur during execution.

When an exception is raised Python looks for a matching except in the current function, then in the caller, and so on up the call stack (propagation).

The first matching except wins.

Use except Exception as e to access the object (message via str(e), type via type(e).

__name__).

Avoid bare except: because it also traps KeyboardInterrupt and SystemExit.

Keep the try block small so you know which line failed, and put code that should run only on success in else.

Prefer EAFP ("easier to ask forgiveness than permission") - try the operation and handle failure - over checking everything in advance (LBYL).

Key points

  • Exception: Object representing an error event.
  • Traceback: Report of the call stack where the exception happened.
  • Propagation: Unhandled exception travelling up to callers.
  • EAFP: Easier to ask forgiveness than permission.

Example

Code
def safe_div(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    else:
        print("division ok")                   # only when no exception
        return result
    finally:
        print("done")                          # always

print(safe_div(10, 2))
# division ok / done / 5.0
print(safe_div(1, 0))
# Cannot divide by zero / done / None

try:
    int("x")
except ValueError as e:
    print("Bad value:", e)                     # invalid literal for int() with base 10: 'x'

def level3(): return 1 / 0
def level2(): return level3()
def level1():
    try:
        level2()
    except ZeroDivisionError:
        print("caught in level1")              # propagated through level3 and level2

level1()
2

How to Catch Multiple Exceptions in Python

Several exception types can be handled either by listing them in a tuple in one except clause - except (TypeError, ValueError) - or by writing separate except clauses, each with its own handling. Python tests clauses top to bottom and runs the first that matches.

In short: One safety net for several kinds of falls, or a different net for each kind.

Think about it

Clause ordering and tuple syntax appear in output-prediction questions. Parsing user JSON: a missing key (KeyError) and a wrong type (TypeError) both produce "invalid input".

Order specific exceptions before general ones: a clause for Exception placed first would swallow everything and later clauses become unreachable.

A tuple is ideal when the handling is identical.

Use as e to learn which one fired.

Exception classes form a hierarchy, so catching a parent such as LookupError also catches KeyError and IndexError, and ArithmeticError covers ZeroDivisionError and OverflowError.

contextlib.

suppress(Err) ignores specific exceptions in a with-block.

Python 3.11 introduced ExceptionGroup and the except* syntax for handling several simultaneous exceptions, mainly in asyncio.

Key points

  • Tuple of exceptions: except (A, B): handles either type.
  • Most specific first: Child classes must come before parent classes.
  • contextlib.suppress: Context manager that ignores listed exceptions.

Example

Code
def parse(items, idx):
    try:
        return int(items[idx])
    except (IndexError, ValueError) as e:      # same handling for both
        return f"bad input ({type(e).__name__})"

print(parse(["10", "x"], 0))                   # 10
print(parse(["10", "x"], 1))                   # bad input (ValueError)
print(parse(["10", "x"], 5))                   # bad input (IndexError)

def lookup(d, key):
    try:
        return 100 / d[key]
    except KeyError:
        return "missing key"
    except ZeroDivisionError:
        return "zero value"
    except Exception as e:                     # general handler LAST
        return f"other: {type(e).__name__}"

print(lookup({"a": 4}, "a"))                   # 25.0
print(lookup({"a": 4}, "b"))                   # missing key
print(lookup({"a": 0}, "a"))                   # zero value
print(lookup({"a": "x"}, "a"))                 # other: TypeError

try:
    {}["k"]
except LookupError:
    print("LookupError catches KeyError")

from contextlib import suppress
with suppress(FileNotFoundError):
    open("no_such_file.txt")
print("continued")
3

Python Raise an Exception

The raise statement triggers an exception deliberately: raise ExceptionClass("message"). A bare raise inside an except block re-raises the active exception. raise NewError from original chains exceptions and stores the cause in __cause__. Custom exceptions are classes that inherit from Exception.

In short: You decide something is wrong and shout. Anything above you in the call stack can catch the shout.

Think about it

Custom exception classes and raise-from are frequent interview coding tasks. A banking function raises InsufficientFunds carrying the missing amount; the UI displays it.

Raise exceptions to signal contract violations (invalid argument, illegal state) instead of returning magic values such as -1.

Choose the closest built-in (ValueError for the right type but wrong value, TypeError for the wrong type) or define a custom class for domain errors, optionally storing extra data on it.

Chaining with from preserves the original traceback; from None hides it.

Re-raising with a bare raise keeps the original traceback intact, which is useful after logging.

assert is for internal sanity checks during development, whereas raise is for run-time validation that must always be active.

Key points

Example

Code
class InsufficientFunds(Exception):
    def __init__(self, needed):
        super().__init__(f"need {needed} more")
        self.needed = needed

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")
    if amount > balance:
        raise InsufficientFunds(amount - balance)
    return balance - amount

try:
    withdraw(50, 80)
except InsufficientFunds as e:
    print(e, e.needed)                         # need 30 more 30

try:
    withdraw(50, -5)
except ValueError as e:
    print("ValueError:", e)

def load_port(text):
    try:
        return int(text)
    except ValueError as err:
        raise RuntimeError("config port is invalid") from err

try:
    load_port("abc")
except RuntimeError as e:
    print(e, "| cause:", repr(e.__cause__))

def process():
    try:
        1 / 0
    except ZeroDivisionError:
        print("logging the error")
        raise                                  # re-raise same exception

try:
    process()
except ZeroDivisionError:
    print("handled by the caller")
4

Finally Keyword in Python

The finally block is attached to a try statement and executes no matter how the try block ends: normal completion, exception, return, break or continue. It is meant for cleanup such as closing files, releasing locks and disconnecting databases.

In short: finally is the "always lock the door when you leave" step, even if you left in a hurry.

finally always runs (cleanup)

Think about it

Predicting output when finally combines with return is a classic tricky question. Always close a database connection even when the query fails.

Order with everything present: try -> (except if error) or (else if no error) -> finally.

When try contains return, the return value is computed first, then finally runs, then the function returns - unless finally itself returns or raises, which overrides the earlier result (avoid this).

If an exception is not handled, finally runs and then the exception continues to propagate.

try/finally without except is valid and common.

For files and locks prefer the with statement, which is a concise, safer form of try/finally.

finally does NOT run if the process is killed or os.

_exit() is called.

Key points

  • finally: Block that always runs after try.
  • Cleanup: Releasing resources like files, sockets, locks.
  • try/finally: Valid without any except clause.

Example

Code
def f():
    try:
        return "try"
    finally:
        print("cleanup runs first")

print(f())                                     # cleanup runs first / try

def g():
    try:
        return 1
    finally:
        return 2                               # overrides: avoid in real code

print(g())                                     # 2

try:
    handle = open("missing_file.txt")
except FileNotFoundError:
    print("file not found")
finally:
    print("always executed")

for i in range(3):
    try:
        if i == 1:
            continue
        print("body", i)
    finally:
        print("finally", i)                    # runs even on continue

def h():
    try:
        1 / 0
    finally:
        print("cleanup then crash propagates")

try:
    h()
except ZeroDivisionError:
    print("caller caught it")
5

Python Built-in Exceptions

Python ships with a hierarchy of exception classes rooted at BaseException. Almost all programmer-level errors derive from Exception. Common ones: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, NameError, AttributeError, FileNotFoundError, ImportError / ModuleNotFoundError, StopIteration, RecursionError, AssertionError and KeyboardInterrupt.

In short: Python already names most mistakes for you: wrong value, wrong type, missing key, bad index, and more.

Try → catch errors safely

Think about it

Matching an error scenario with the correct exception name is a standard objective question. int("abc") -> ValueError; [1,2][9] -> IndexError; {"a":1}["b"] -> KeyError; open("x") -> FileNotFoundError.

Hierarchy highlights: BaseException -> (SystemExit, KeyboardInterrupt, GeneratorExit, Exception).

Under Exception: ArithmeticError (ZeroDivisionError, OverflowError, FloatingPointError), LookupError (IndexError, KeyError), OSError (FileNotFoundError, PermissionError, TimeoutError), ValueError (UnicodeError), NameError (UnboundLocalError), ImportError (ModuleNotFoundError), RuntimeError (RecursionError, NotImplementedError), SyntaxError and AssertionError.

Catch Exception, not BaseException, in general application code.

Warnings (DeprecationWarning, UserWarning) are not exceptions unless escalated.

Use help(ExceptionName) or the official docs to look up the full tree.

Key points

  • BaseException: Root of every exception class.
  • LookupError: Parent of IndexError and KeyError.
  • ArithmeticError: Parent of ZeroDivisionError and OverflowError.
  • OSError: Parent of file/system errors like FileNotFoundError.

Example

Code
tests = [
    ("division",   lambda: 1 / 0),
    ("conversion", lambda: int("a")),
    ("type",       lambda: "a" + 1),
    ("index",      lambda: [1][5]),
    ("key",        lambda: {}["k"]),
    ("name",       lambda: undefined_name),
    ("attribute",  lambda: (5).foo),
    ("file",       lambda: open("missing.txt")),
    ("import",     lambda: __import__("no_such_module")),
    ("iterator",   lambda: next(iter([]))),
]

for label, action in tests:
    try:
        action()
    except Exception as e:
        print(f"{label:11} -> {type(e).__name__}: {e}")

print(issubclass(KeyError, LookupError))               # True
print(issubclass(ZeroDivisionError, ArithmeticError))  # True
print(issubclass(FileNotFoundError, OSError))          # True
print(issubclass(KeyboardInterrupt, Exception))        # False (BaseException only)

def recurse():
    return recurse()

try:
    recurse()
except RecursionError:
    print("RecursionError: maximum recursion depth exceeded")

Solved examples

Example 01 · Basic

Read an integer from a string safely: print the number, or "Invalid" if conversion fails.

Given Data:
    Required To Find:

    Code

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Put int(text) inside try
    Step 2: Catch ValueError
    Step 3: Print the fallback message
    Final Answer: text = "12a" try: print(int(text)) except ValueError: print("Invalid") # Invalid

    Approach note: Catch the narrowest exception that can occur.

    Example 02 · Intermediate

    What does this print? def f(): try: return "A" finally: print("B") print(f())

    Given Data:
      Required To Find:

      Printed lines

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: return "A" evaluates the value
      Step 2: finally runs and prints B
      Step 3: Function returns "A", which is printed
      Final Answer: B A

      Approach note: finally always runs before control leaves the try statement.

      Example 03 · Intermediate

      Write a function set_age(age) that raises ValueError for ages outside 0-120.

      Given Data:
        Required To Find:

        Function

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Check the range
        Step 2: raise ValueError with a helpful message
        Step 3: Return the age otherwise
        Final Answer: def set_age(age): if not 0 <= age <= 120: raise ValueError("age must be between 0 and 120") return age

        Approach note: Validate early and raise a specific exception.

        Example 04 · Basic

        What prints for: try: print(10 / 0) except ZeroDivisionError: print("oops") else: print("ok") finally: print("done")

        Given Data:
          Required To Find:

          Output lines

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: 10/0 raises ZeroDivisionError
          Step 2: except runs and prints oops
          Step 3: else is skipped because an exception occurred
          Step 4: finally always runs and prints done
          Final Answer: oops done

          Approach note: else runs only when no exception; finally always runs.

          Real-world applications

          Python

          Using Python Exception Handling in real projects

          Input validation, file and network I/O, database transactions, APIs and long-running services.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: except: and except Exception: are identical.

          Why this is wrong: Bare except also catches KeyboardInterrupt and SystemExit.

          ✅ Verified Truth: Use except Exception (or narrower).

          ⚠️ Exam Tip: Say "bare except hides Ctrl+C".

          ❌ Myth: finally runs only if an exception occurs.

          Why this is wrong: It runs in every case.

          ✅ Verified Truth: Success, failure, return, break and continue all run finally.

          ⚠️ Exam Tip: Use it for cleanup, not for error handling.

          ❌ Myth: The order of except blocks does not matter.

          Why this is wrong: The first matching clause wins.

          ✅ Verified Truth: Place specific exceptions before parents.

          ⚠️ Exam Tip: A parent first makes later clauses unreachable.

          Revision notes

          An exception is an error detected at run time that interrupts normal flow. Python lets you catch it with try/except/else/finally, raise your own, handle several types and rely on a rich hierarchy of built-in exceptions.

          High-Yield Quick Revision Points

          1. try -> except -> else (no error) -> finally (always).
          2. Order except clauses specific to general; avoid bare except.
          3. raise Err("msg"); bare raise re-raises; raise X from Y chains.
          4. finally runs even after return/break/continue.
          5. KeyError/IndexError are LookupError; ZeroDivisionError is ArithmeticError.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which block runs only when no exception occurs in try?

          Question 2 · MCQ (Interview / semester)

          int("abc") raises

          Question 3 · MCQ (Interview / semester)

          [1, 2, 3][10] raises

          Question 4 · MCQ (Interview / semester)

          Which statement chains exceptions?

          Question 5 · MCQ (Interview / semester)

          Custom exceptions should usually inherit from

          Question 6 · MCQ (Interview / semester)

          Which is the correct syntax for two exceptions in one clause?