Quest 1 • Lesson 9
⚠️ Error Handling (try/except)
Errors in Python are called exceptions. Instead of crashing, you can handle them gracefully using try and except. This makes your programs robust and user‑friendly.
"Good error handling turns a crash into a helpful message. It's what separates beginner code from professional code."
try_except.py
try:
num = int(input("Enter a number: "))
print(f"You entered: {num}")
except ValueError:
print("That's not a valid number!")
num = int(input("Enter a number: "))
print(f"You entered: {num}")
except ValueError:
print("That's not a valid number!")
🧠 How it Works
try– block of code that might raise an error.except– runs if an error occurs.- You can catch specific errors (e.g.,
ValueError,ZeroDivisionError). - If no error occurs, the
exceptblock is skipped.
multiple_except.py
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print(result)
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print(f"Something went wrong: {e}")
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print(result)
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print(f"Something went wrong: {e}")
finally.py
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed.") # Always runs
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed.") # Always runs
📌 The finally Block
- Runs always – whether an error occurred or not.
- Useful for cleanup: closing files, releasing resources.
🔧 Bonus: raise – Manually Trigger Errors
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return f"Age: {age}"
if age < 0:
raise ValueError("Age cannot be negative!")
return f"Age: {age}"
Use raise to enforce constraints and make your code more predictable.
🧪 Interactive Playground
Enter two numbers to divide (with error handling).
Click "Divide" to test error handling.
✨ Challenge: Safe Input Function
Write a function safe_int_input(prompt) that:
- Uses
try/exceptto catchValueError. - Keeps asking until the user enters a valid integer.
- Returns the integer.
def safe_int_input(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid number. Try again.")
age = safe_int_input("Enter your age: ")
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid number. Try again.")
age = safe_int_input("Enter your age: ")
❤️ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
☕ Buy Me a Coffee➡️ Almost there!
Next lesson: Mini Project – Calculator (final Python Quest 1 lesson).
Continue to Lesson 1.10 →(Coming soon – check back or buy Pro Pack for instant access)