Goal

You’ll be able to handle errors gracefully using try/except, and understand why catching a specific exception type is genuinely better practice than catching every possible error the same way.

Learn

When Python encounters an error it can’t recover from on its own, it raises an exception, which crashes the program unless it’s handled:

age = int(input("Age: "))  # crashes if user types "abc"

try/except lets you handle this gracefully instead of crashing:

try:
    age = int(input("Age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("Please enter a valid number.")

The code inside try runs normally; if it raises the specific exception named in except, that block runs instead of crashing the whole program. Different operations raise different exception types — ValueError (invalid value for a conversion), ZeroDivisionError (dividing by zero), KeyError (missing dictionary key, from Part 2.4), and many others.

Here’s a genuinely important practice: catching a specific exception type, like except ValueError:, is much better than a broad, catch-everything except:. A bare except silently swallows any error — including genuine bugs in your own code that you’d actually want to know about — making debugging significantly harder, since real problems get hidden rather than surfaced:

# Risky: hides genuine bugs along with expected errors
try:
    result = risky_operation()
except:
    print("Something went wrong.")

# Better: only catches the specific error you actually expect
try:
    result = risky_operation()
except ValueError:
    print("Invalid value provided.")

Decision Task

A program has a genuine typo bug (like a misspelled variable name) inside a try block that also happens to catch potential ValueError from user input, using a bare except:. Before reading on: what real problem does this create when trying to find and fix the typo bug?

Show Answer

The bare except: silently catches the typo bug (a NameError) the exact same way it catches the expected ValueError, hiding the real bug behind a generic “something went wrong” message instead of a clear, specific error pointing at the actual typo. This makes the genuine bug significantly harder to find and fix, since it’s indistinguishable from the expected, handled error case.

Common Mistake

Using a bare except: (catching every possible error identically) instead of naming the specific exception type actually expected. This silently swallows real bugs in your own code right alongside genuinely expected errors, making debugging significantly harder — a real programming mistake gets hidden and reported the same generic way as a normal, anticipated user input error.

Practice Questions

1. Write a try/except block that attempts to convert user input to an integer, printing “Invalid number” if it fails.

Show Answer

try:\n value = int(input("Enter a number: "))\nexcept ValueError:\n print("Invalid number")

2. What exception type is typically raised when trying to convert something like “abc” to an integer?

Show Answer

ValueError

3. Why is catching a specific exception type generally better practice than a bare except:?

Show Answer

A bare except: catches every possible error identically, including genuine bugs unrelated to the expected error case, making those real bugs harder to find since they’re silently hidden behind the same generic handling.

4. True or False: code inside a try block that doesn’t raise any exception will simply run normally, skipping the except block entirely.

Show Answer

True — the except block only runs if an exception matching its specified type is actually raised inside the try block.

5. What exception type, covered in Part 2.4, is raised when accessing a dictionary key that doesn’t exist?

Show Answer

KeyError

Try It Yourself

Without looking back, write a try/except block that attempts a division (like 10 / user_input) and specifically handles ZeroDivisionError with a friendly message.

Show Answer

try:\n result = 10 / user_input\nexcept ZeroDivisionError:\n print("Cannot divide by zero.") — catching the specific ZeroDivisionError type, not a bare except.

Quick Check

1. What does try/except let a program do?

Show Answer

Handle an error gracefully instead of crashing the entire program.

2. What exception type is raised by an invalid type conversion, like int(“abc”)?

Show Answer

ValueError

3. Why is a bare except: generally considered risky practice?

Show Answer

It silently catches every possible error identically, including genuine bugs, making debugging harder since real problems are hidden behind generic handling.

4. What exception type is raised by dividing by zero?

Show Answer

ZeroDivisionError

5. What exception type is raised by accessing a missing dictionary key?

Show Answer

KeyError

تحميل هذا الباب / Download this Chapterنسخة كاملة للدراسة بدون إنترنت، مع الأسئلة والإجابات والصور المتاحة.