🛡️ What is an exception?

An exception is an error that occurs while your program runs. Python stops at that line and raises an exception — it's a signal that something went wrong.

try: attempt risky code
except: handle the mistake

Without exception handling, a single error crashes your whole program. With try/except, you catch the error, log it, and decide what to do next — keep running, fix the data, or ask the user to try again.

🎯 Common exception types

ValueError
int("abc")
Wrong value type for a conversion.
ZeroDivisionError
100 / 0
Division by zero.
FileNotFoundError
open("missing.txt")
File does not exist.
KeyError
dict["bad_key"]
Dictionary key not found.
IndexError
list[999]
List index out of range.
AttributeError
obj.missing_attr
Object has no such attribute.

🏦 The business scenario

🏦
Banking · SouthBank India
Processing customer-uploaded CSVs

SouthBank India's Mumbai branch accepts customer transaction records as CSV uploads. Rows might have missing fields, non-numeric amounts, or invalid dates. Instead of rejecting the entire file, your job is to parse each row, catch errors, log them, and process the good ones. You also need to retry payment API calls that sometimes time out.

12,450
Daily CSV uploads
8–15%
Rows with errors
₹500K+
Avg transaction value

💻 Step-by-step worked example

Step 1: What happens without try/except

Here's what crashes:

code1 — crash demoWithout try/except
Output
ValueError: invalid literal for int() with base 10: 'abc' Process crashed.

Step 2: Basic try/except for a single row

Now catch the error and skip bad rows:

code2 — basic try/exceptCatch ValueError on CSV row
Output
✗ Skipped Priya: invalid amount 'abc'

Step 3: else + finally for cleanup

Use else to run code only if no error occurred. Use finally to always clean up (close files, log, etc.):

code3 — try/except/else/finallyFile read pattern with cleanup
Output
✓ Parsed 5 rows ✓ Cleanup complete

Step 4: raise + retry loop for APIs

Sometimes you want to throw your own exception. Use raise to throw a custom error or re-raise an existing one. Use a loop to retry failed API calls:

code4 — raise + retry loopCustom exception + API retry
Output (example run)
⟳ Retry 1/3: API timeout ⟳ Retry 2/3: API timeout ✓ Payment of ₹15000 succeeded on attempt 3

🌍 Where error handling appears

Used across every domain

🏦
Banking & Fintech
Retry payment APIs, validate account numbers, catch invalid transaction formats. M-Pesa Kenya logs failed transfers and alerts users.
🛒
E-commerce
Handle missing product inventory, bad customer input, failed database writes. Gracefully tell the user what went wrong.
🔐
Security & Auth
Catch failed login attempts, invalid tokens, permission denials. Log security events without exposing internals.
📡
APIs & Data
Handle network timeouts, malformed JSON responses, rate limiting. Retry or queue for later.

🤖 AI & Exception handling

How AI models use exception handling

When a language model encounters a malformed input (bad JSON, missing field, out-of-range number), it catches the parsing error, returns a structured error response, and lets the application decide whether to retry, use a default, or ask the user. Exception handling is how AI services stay resilient and predictable.

Data validation Graceful degradation Retry logic Error logging

⚡ Mini challenge

Task: Write a function that reads a list of prices (strings) and converts them to floats. If a price is invalid, log it and skip it. Return the valid prices and count of errors.

Example:

prices = ["₹500", "abc", "₹200.50", "xyz"]

Expected output:

Valid: [500.0, 200.50], Errors: 2
Hint: Use try/except ValueError in a loop. For each price, try float(price.replace("₹", "")). If it fails, increment an error counter. Append successful conversions to a results list.

💬 Interview Q&A

A bare except: catches everything — including KeyboardInterrupt (Ctrl+C) and SystemExit (program quit), which you usually don't want to catch. except Exception: is safer because it only catches actual application errors, not system signals. Always prefer except Exception: or catch specific types.

The else block runs only if no exception occurred in the try block. It's useful for code that should only run on success — like processing valid data or logging success metrics. If an exception is raised and caught, else is skipped.

finally always runs, whether an exception occurred or not. Use it to clean up resources — close files, release database connections, log completion. Even if an exception is re-raised after finally, the finally block runs first.

Use raise when you detect an invalid state that the caller needs to know about. Example: a function that validates a bank account number should raise ValueError("Account must be 10 digits") if it's wrong. This forces the caller to handle it with their own try/except.

Python exceptions inherit from BaseException. Most application errors inherit from Exception. Specific types like ValueError, KeyError, FileNotFoundError inherit from Exception. The hierarchy matters because a except Exception: catches ValueError but not KeyboardInterrupt. You can catch parent classes to handle multiple child types, or be specific to handle only expected errors.

📚 Quiz

Question 1 of 5
Which exception is raised when dividing by zero?
Question 2 of 5
What happens if no exception occurs in a try block?
Question 3 of 5
Which of these catches a KeyError from a missing dictionary key?
Question 4 of 5
The finally block runs:
Question 5 of 5
What does raise do?
0
/ 5
Great effort!

📋 Cheatsheet

Concept Syntax / Example
Basic try/except try: x = int("a")
except ValueError: print("Bad")
Catch specific type except ZeroDivisionError as e: print(e)
Catch multiple types except (ValueError, KeyError): ...
else (success path) try: ... except: ...
else: print("Success")
finally (cleanup) try: ... except: ...
finally: file.close()
Re-raise exception except E: log(E)
raise
Throw custom error if amount < 0:
raise ValueError("Negative")
Get error message except ValueError as e: print(str(e))

⚠️ Common mistakes

Bare except: catches too much
Bad: except: catches KeyboardInterrupt (Ctrl+C), so you can't interrupt the program.
Better: except Exception: or catch specific types.
Swallowing the exception silently
Bad: except ValueError: pass — you'll never know an error happened.
Better: except ValueError: print("Bad input"); log_error() — always log or inform.
Catching too broad a scope
Bad: try: entire_function(); except Exception: ... — hides bugs deep in the code.
Better: try: risky_line(); except ValueError: ... — be specific about what might fail.
Forgetting to close files in finally
Bad: f = open("data.txt") without finally: f.close().
Better: Use with open("data.txt") as f: (context manager) — it auto-closes.

✦ Key takeaways

  • Exceptions are signals. They tell you when something goes wrong. Python stops at that line and jumps to the nearest except block.
  • Catch specific types. Use except ValueError: or except (ValueError, KeyError): — avoid bare except:.
  • else runs on success. Code in the else block only runs if no exception occurred in try.
  • finally always runs. Use it to close files, release resources, and log completion — essential for cleanup.
  • Use raise to throw. Validate your inputs and raise custom exceptions so callers know what went wrong.
  • Retry loops are common. Network calls, APIs, and flaky operations benefit from retry logic inside try/except blocks.