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
try:
# risky code
except ErrorType1:
# handle first error
except ErrorType2:
# handle second error
Example: Number Input + Division
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
Enter number: hello
Please enter a valid number
Example Output 2
Enter number: 0
You cannot divide by zero
Example: File + Number
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.
try:
number = int(input("Enter number: "))
print(10 / number)
except (ValueError, ZeroDivisionError):
print("Invalid input")
Output Example
Invalid input
Common Error Types
ValueErrorZeroDivisionErrorFileNotFoundErrorIndexErrorTypeError
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:
items = ["Pen", "Book"]
- Ask user for index
- Print item at that index
- Handle:
- bad number input
- wrong index
Expected output:
Enter index: 5
Index not found
Real World Use Case
Programs handle different errors in forms, banking apps, reports, uploads, and user tools.
Quiz
- Why use multiple
exceptblocks? - What error happens when dividing by zero?
- What error happens when a file is missing?
- 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.