Exception Handling
Exception Handling
Sometimes programs crash when something goes wrong.
Examples:
- Dividing by zero
- Typing text instead of a number
- Opening a missing file
- Using a wrong index
Python calls these problems exceptions.
We can handle them so the program does not crash.
What Is an Exception?
An exception is an error that happens while the program is running.
Without handling it, the program stops.
Why Exception Handling Matters
It helps programs:
- Keep running
- Show friendly messages
- Handle bad input
- Avoid crashes
Example Without Handling
number = int(input("Enter number: "))
print(number)
If the user types:
hello
The program crashes.
Using try and except
Use try for risky code.
Use except to handle errors.
try:
number = int(input("Enter number: "))
print(number)
except:
print("Please enter a valid number")
Example Output
Enter number: hello
Please enter a valid number
Divide by Zero Example
try:
result = 10 / 0
print(result)
except:
print("Cannot divide by zero")
Output
Cannot divide by zero
File Example
try:
with open("missing.txt") as file:
print(file.read())
except:
print("File not found")
Output
File not found
Catch Specific Errors
You can catch a specific error type.
try:
number = int("hello")
except ValueError:
print("That is not a number")
Output
That is not a number
Another Example
try:
items = [1, 2]
print(items[5])
except IndexError:
print("Index does not exist")
Output
Index does not exist
Good Practice
Use clear error messages.
Help the user know what to fix.
Code Along
Build a safe age checker.
Steps:
- Ask for age
- Convert to number
- If invalid input, show message
Mini Challenge
Build a safe calculator.
Steps:
- Ask for two numbers
- Add them
- If user enters bad input, print:
Invalid number
Expected output:
Enter first number: hi
Invalid number
Real World Use Case
Apps use exception handling for forms, files, payments, APIs, and user input.
Quiz
- What is an exception?
- What does
trydo? - What does
exceptdo? - Why is exception handling useful?
Assignment
Create a program that asks for a number and prints its double. Handle invalid input safely.
Summary
You learned how to stop crashes and handle errors using try and except in Python.