🛡️ 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.
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
🏦 The business scenario
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.
💻 Step-by-step worked example
Step 1: What happens without try/except
Here's what crashes:
Step 2: Basic try/except for a single row
Now catch the error and skip bad rows:
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.):
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:
🌍 Where error handling appears
Used across every domain
🤖 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.
⚡ 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
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
📋 Cheatsheet
| Concept | Syntax / Example |
|---|---|
| Basic try/except | try: x = int("a") |
| Catch specific type | except ZeroDivisionError as e: print(e) |
| Catch multiple types | except (ValueError, KeyError): ... |
| else (success path) | try: ... except: ... |
| finally (cleanup) | try: ... except: ... |
| Re-raise exception | except E: log(E) |
| Throw custom error | if amount < 0: |
| Get error message | except ValueError as e: print(str(e)) |
⚠️ Common mistakes
except: catches KeyboardInterrupt (Ctrl+C), so you can't interrupt the program.Better:
except Exception: or catch specific types.
except ValueError: pass — you'll never know an error happened.Better:
except ValueError: print("Bad input"); log_error() — always log or inform.
try: entire_function(); except Exception: ... — hides bugs deep in the code.Better:
try: risky_line(); except ValueError: ... — be specific about what might fail.
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
exceptblock. - Catch specific types. Use
except ValueError:orexcept (ValueError, KeyError):— avoid bareexcept:. - else runs on success. Code in the
elseblock only runs if no exception occurred intry. - finally always runs. Use it to close files, release resources, and log completion — essential for cleanup.
- Use raise to throw. Validate your inputs and
raisecustom 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.