CodingNic

Error Handling and Debugging

Multiple Exceptions

Error Handling and Debugging 24 min read

Multiple Exceptions

Multiple Exceptions

Different errors can happen in the same program.

For example:

  • Text instead of a number
  • Division by zero
  • Missing file
  • Wrong list index

Python lets you handle different errors in different ways.

Why This Matters

Different problems need different messages.

Instead of showing one generic message, you can explain the real issue.

Basic Structure

python
try:
    # risky code
except ErrorType1:
    # handle first error
except ErrorType2:
    # handle second error

Example: Number Input + Division

python
try:
    number = int(input("Enter number: "))
    result = 10 / number
    print(result)

except ValueError:
    print("Please enter a valid number")

except ZeroDivisionError:
    print("You cannot divide by zero")

Example Output 1

text
Enter number: hello
Please enter a valid number

Example Output 2

text
Enter number: 0
You cannot divide by zero

Example: File + Number

python
try:
    with open("data.txt") as file:
        text = file.read()

    age = int(input("Enter age: "))
    print(age)

except FileNotFoundError:
    print("The file was not found")

except ValueError:
    print("Age must be a number")

Why Order Matters

Python checks except blocks from top to bottom.

Put specific errors first.

Catch Many Errors in One Block

You can group errors.

python
try:
    number = int(input("Enter number: "))
    print(10 / number)

except (ValueError, ZeroDivisionError):
    print("Invalid input")

Output Example

text
Invalid input

Common Error Types

  • ValueError
  • ZeroDivisionError
  • FileNotFoundError
  • IndexError
  • TypeError

Code Along

Build a safe score checker.

Steps:

  • Ask for score
  • Convert to number
  • Divide 100 by score
  • Handle:
    • bad input
    • zero

Mini Challenge

Build a safe list reader.

Steps:

  • Create a list:
python
items = ["Pen", "Book"]
  • Ask user for index
  • Print item at that index
  • Handle:
    • bad number input
    • wrong index

Expected output:

text
Enter index: 5
Index not found

Real World Use Case

Programs handle different errors in forms, banking apps, reports, uploads, and user tools.

Quiz

  1. Why use multiple except blocks?
  2. What error happens when dividing by zero?
  3. What error happens when a file is missing?
  4. Why does order matter?

Assignment

Create a program that asks for a number and prints an item from a list using that index. Handle both ValueError and IndexError.

Summary

You learned how to catch different errors separately and show better messages for each problem.