CODE PATH
PRO ACCOUNT

Master Code
On The Go

Learn. Practice. Build.

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!")

🧠 How it Works

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}")
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

📌 The finally Block

🔧 Bonus: raise – Manually Trigger Errors

def check_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:

❤️ 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)