Exception Handling
Gracefully handle errors in your code using try, except, and finally.
๐ก๏ธ Introduction: The "Safety Net"
Imagine a trapeze artist performing in a circus. If they slip and fall, they don't hit the ground and die. Why? Because there is a Safety Net below them.
In Python programming:
1. The Program is the trapeze artist.
2. An Error (Exception) is the artist slipping.
3. The try...except block is the safety net.
Without this safety net, when an error happens (like dividing by zero or opening a missing file), your program crashes immediately (hits the ground). With the safety net, you "catch" the error and handle it gracefully.
โ ๏ธ Topic 1: What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It is Python's way of saying, "Something went wrong, and I don't know what to do next!"
๐จ The "Big 4" Exceptions:
10 / 0
int("hello")
"A" + 5
list[100] (when list has 5 items)
๐ฅ The Crash Zone:
This code has no safety net. Run it, and it dies instantly.
x = 10 / 0 # CRASH!
print("End") # This never runs
๐ก๏ธ Topic 2: The try...except Block
This structure allows you to "try" a dangerous piece of code, and "catch" the error if it fails, instead of letting the program crash.
๐ Syntax Breakdown:
# Risky code goes here
except ExceptionType:
# Rescue code goes here
๐ป Example: Safe Division
๐ฏ Topic 3: Catching Specific Errors
Not all errors are the same. A "File Not Found" error is different from a "Math Error". Python allows you to catch them separately to provide better feedback.
Analogy: If you go to a doctor, they treat a "Broken Leg" differently from a "Headache". You don't just say "I have a problem" (Generic Exception).
๐ป Example: The Multi-Catcher
๐ก Best Practice:
Always catch specific errors first. Only use except Exception: at the very end as a fallback.
๐งน Topic 4: The finally Block
The finally block is the "Cleanup Crew". It executes NO MATTER WHAT.
- If try succeeds -> finally runs.
- If try fails (catch error) -> finally runs.
- If try crashes (uncaught error) -> finally STILL runs (before crash).
๐ป Example: File Handling
๐ฉ Topic 5: Raising Exceptions
Sometimes, you want to stop the program yourself when a rule is broken (even if Python doesn't think it's an error). You can use the raise keyword.
๐ป Example: Age Validation
๐ Quick Cheat Sheet
- try: The code you want to test (the dangerous part).
- except: The code to run if an error happens.
- else: Runs only if NO exceptions occurred.
- finally: Always runs (cleanup).
- raise: Manually trigger an error.
๐ค Interview Q&A
Tap on the questions below to reveal the answers.
Python checks them from top to bottom. As soon as it finds a matching exception type, it executes that block and skips the rest. That's why you should put specific exceptions (like ZeroDivisionError) first and generic ones (like Exception) last.
No, a try block must be followed by at least one except OR a finally block. You cannot have a standalone try.
A bare except looks like except: with no error type specified. It catches EVERYTHING, including system exit signals (like Ctrl+C). This makes debugging very hard because it hides real bugs. Always use except Exception: instead.
The else block runs ONLY if the code in the try block executed successfully without raising any exceptions.