Python Lesson 17: Error Handling

🐍 Python CourseLesson 17 of 26 · 65% complete

Errors are normal. Professional Python code handles errors gracefully so the program does not crash when something unexpected happens.

Types of Errors

# SyntaxError — broken code structure
# print("hello)  ← missing quote

# TypeError — wrong type operation
# "hello" + 5  ← cannot add str and int

# ValueError — wrong value
# int("abc")  ← cannot convert "abc" to int

# IndexError — list index out of range
# [1,2,3][10]  ← index 10 does not exist

# KeyError — dictionary key not found
# {"a":1}["b"]  ← key "b" does not exist

# ZeroDivisionError
# 10 / 0  ← cannot divide by zero

try / except

try:
    age = int(input("Enter your age: "))
    print(f"Next year: {age + 1}")
except ValueError:
    print("Please enter a valid number!")

# Multiple except blocks
try:
    number = int(input("Enter number: "))
    result = 100 / number
    print(f"100 / {number} = {result}")
except ValueError:
    print("Not a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

else and finally

try:
    result = int(input("Number: "))
except ValueError:
    print("Invalid input!")
else:
    # runs only if NO exception occurred
    print(f"You entered: {result}")
finally:
    # ALWAYS runs, error or not
    print("Done!")

Raising Your Own Errors

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

try:
    print(divide(10, 0))
except ValueError as e:
    print(f"Error: {e}")

🏋️ Practice Task

Build a robust number converter. Ask user to enter a number. Handle: (1) ValueError if they type text, (2) tell them to try again in a loop until they enter a valid number. Then check if it’s positive, negative, or zero.

💡 Hint: Use while True: with try/except ValueError inside. Use break when successful input is received.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *