DSPython Logo DSPython

Exception Handling

Gracefully handle errors in your code using try, except, and finally.

Python Basics Beginner 30 min

๐Ÿ›ก๏ธ 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:

ZeroDivisionError

10 / 0

ValueError

int("hello")

TypeError

"A" + 5

IndexError

list[100] (when list has 5 items)

๐Ÿ’ฅ The Crash Zone:

This code has no safety net. Run it, and it dies instantly.

print("Start")
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:

try:
    # Risky code goes here
except ExceptionType:
    # Rescue code goes here

๐Ÿ’ป Example: Safe Division

# Let's handle the zero division gracefully
try:
numerator = 100
denominator = 0
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Oops! You cannot divide by zero.")

print("Program continues normally...")

# Output:
# Oops! You cannot divide by zero.
# Program continues normally...

๐ŸŽฏ 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

try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Hey! That is not a number.")
except ZeroDivisionError:
print("Math Error: Division by 0 is illegal.")
except Exception as e:
# This catches EVERYTHING else (The Backup Plan)
print(f"Something unexpected happened: {e}")

๐Ÿ’ก 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

try:
file = open("important_data.txt", "r")
# Perform operations...
except FileNotFoundError:
print("File not found!")
finally:
# This ensures file is closed even if error occurs
print("Closing file/database connection...")

๐Ÿšฉ 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

age = -5

if age < 0:
# Python allows negative numbers, but our logic doesn't!
raise ValueError("Age cannot be negative!")

๐Ÿ“š 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.