Skip to main content

Exception Handling

Teaching Code to Survive Mistakes

Imagine you’re a hacker infiltrating a system. Suddenly, something unexpected happens like an invalid password, a missing file, or a broken connection. If your script crashes, the mission fails. What you need is resilience: the ability for your program to handle errors gracefully and keep running.

In Python, this resilience comes from exception handling. With try, except, finally, and raise, you can anticipate problems, catch them when they occur, and respond intelligently. This chapter is about building robust programs that don’t collapse under pressure.


Why Exception Handling Matters

  • Errors vs Exceptions:
    • Errors are problems in code logic (like syntax errors).
    • Exceptions occur during execution (like dividing by zero).
  • Handling Exceptions: Instead of crashing, Python lets you catch exceptions and decide what to do.
  • Robustness: Exception handling makes programs reliable, especially when dealing with unpredictable input or external resources.
  • Hacker’s Advantage: Anticipating failure is part of the craft and robust programs survive chaos.

Basic Try/Except

try:
    num = int(input("Enter a number: "))
    print("Result:", 10 / num)
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
except ValueError:
    print("Error: Invalid input. Please enter a number.")
  • Why? The program doesn’t crash on bad input, it responds with clear feedback.

Finally Block

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Error: File not found.")
finally:
    print("Execution complete.")
  • Why? finally runs no matter what like closing files or releasing resources.

Raising Exceptions

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    print(check_age(-5))
except ValueError as e:
    print("Caught exception:", e)
  • Why? raise lets you trigger exceptions intentionally when invalid data is detected.

Exceptions & Custom Handling

try:
    x = int("abc")
    y = 10 / 0
except (ValueError, ZeroDivisionError) as e:
    print("Caught exception:", e)
  • Why? Grouping exceptions simplifies handling when multiple errors are possible.

The Hacker’s Notebook

  • Exceptions are runtime problems so catch them to prevent crashes. try/except blocks let you respond gracefully to errors.
  • finally ensures cleanup, even if errors occur. raise allows you to enforce rules by triggering exceptions intentionally.

Hacker’s Mindset: treat exceptions as battle drills. Anticipate failure, catch it, and recover without breaking your mission.


Tips, Tricks, Roadmaps, Resources, Networking, Motivation, Guidance, and Cool Stuff ♥

Updated on Jan 2, 2026