Module 5 Lesson 7: Specific vs. Generic Exceptions
·Programming

Module 5 Lesson 7: Specific vs. Generic Exceptions

Precision error handling. Learn why catching 'every' exception is risky and how to target specific errors like FileNotFoundError and ZeroDivisionError.

Module 5 Lesson 7: Specific vs. Generic Exceptions

In the last lesson, we used a "catch-all" except: block. While this prevents crashes, it’s like using a sledgehammer to fix a watch. If you catch EVERY error, you might accidentally hide a serious bug (like a typo in your variable name) that you actually want to see. In this lesson, we’ll learn how to be precise.

Lesson Overview

In this lesson, we will cover:

  • The Danger of "Bare" Excepts: Why except: is often a bad idea.
  • Common Python Exceptions: ValueError, IndexError, KeyError, etc.
  • Multiple Except Blocks: Handling different errors in different ways.
  • The as Keyword: Inspecting the error message itself.

1. Why Specificity Matters

If you use a bare except:, you won't know why your code failed. Was the file missing? Or was the math wrong? Or did you misspell a function name?

# BAD CODE
try:
    x = 1 / 0
except:
    print("Something went wrong.") # Was it a divide by zero or a typo?

2. Catching Specific Errors

You can name the specific exception you want to catch immediately after the except keyword.

try:
    num = int(input("Enter a number: "))
    result = 100 / num
except ValueError:
    print("Error: You must enter a valid number (e.g., 10), not a word.")
except ZeroDivisionError:
    print("Error: You cannot divide by zero!")

3. The as e Pattern

Sometimes you want to see the actual error message that Python generated. We use as to store the error in a variable (usually named e).

try:
    with open("ghost_file.txt", "r") as file:
        pass
except FileNotFoundError as e:
    print(f"System says: {e}") 
    # Output: System says: [Errno 2] No such file or directory: 'ghost_file.txt'

4. Common Exceptions to Know

  • IndexError: You tried to access my_list[10] but the list only has 3 items.
  • KeyError: You tried to find a key in a dictionary that doesn't exist.
  • TypeError: You tried to add a string and an integer ("5" + 2).
  • NameError: You used a variable name that hasn't been defined yet.

Practice Exercise: The Safe List Accessor

  1. Create a list of 5 colors.
  2. Ask the user for an index number (0-4).
  3. Try to print the color at that index.
  4. Use specific except blocks to handle:
    • ValueError: If the user enters a word instead of a number.
    • IndexError: If the user enters a number too high (like 10).
  5. Add a generic except Exception: at the very bottom to catch anything else.

Quick Knowledge Check

  1. Why is a "bare" except: risky for debugging?
  2. How do you handle two different types of errors in one try block?
  3. What does the as keyword do in an except block?
  4. Which exception happens when you try to use a key that isn't in a dictionary?

Key Takeaways

  • Always try to catch narrow, specific exceptions first.
  • Specific handling allows for better error messages for the user.
  • The as keyword lets you inspect the technical details of an error.
  • The Exception class is the "parent" of all errors and can be used as a final fallback.

What’s Next?

We’ve learned how to catch errors that Python throws at us. But what if we want to stop the program because a user did something "legal" but wrong (like trying to buy a $100 item with only $50)? In Lesson 8, we’ll learn how to Raise Custom Exceptions!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn