š
Error Handling and Exceptions
Beginner
90 XP
35 min
Lesson Content
Error Handling: Dealing with Problems
Errors happen in programming. Learning to handle them gracefully makes your programs more robust and user-friendly.
Common Error Types
# SyntaxError - Code syntax is wrong
# if x = 5: # Error! Should be ==
# NameError - Variable doesn't exist
# print(undefined_var) # Error!
# TypeError - Wrong data type
# "5" + 3 # Error! Can't add string and int
# ValueError - Wrong value
# int("hello") # Error! Can't convert to int
# IndexError - List index out of range
# my_list = [1, 2, 3]
# print(my_list[10]) # Error!
# KeyError - Dictionary key doesn't exist
# my_dict = {"a": 1}
# print(my_dict["b"]) # Error!The try-except Block
Handle errors gracefully:
# Basic error handling
try:
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except ValueError:
print("That's not a valid number!")
# Multiple exceptions
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError:
print("Wrong data type!")try-except-else-finally
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"Success! You entered: {number}")
finally:
print("This always runs, even if there's an error")Handling Multiple Exceptions
try:
# Some code that might fail
value = my_list[index] / divisor
except (IndexError, ZeroDivisionError):
print("Either index is wrong or division by zero!")
except Exception as e:
print(f"An error occurred: {e}")Raising Exceptions
Create your own errors:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age > 150:
raise ValueError("Age seems unrealistic!")
return age
try:
check_age(-5)
except ValueError as e:
print(f"Error: {e}")Best Practices
- ā Be specific with exception types
- ā Don't catch all exceptions unless necessary
- ā Provide helpful error messages
- ā Use finally for cleanup code
- ā Log errors for debugging
Common Patterns
# Safe division
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
# Safe input
def get_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a valid number!")Example Code
Create a safe calculator that handles errors.
# Safe calculator function
def safe_calculate(a, b, operation):
try:
if operation == "add":
return a + b
elif operation == "divide":
return a / b
else:
return "Unknown operation"
except ZeroDivisionError:
return "Error: Cannot divide by zero"
except Exception as e:
return f"Error: {e}"
# Test the function
print(safe_calculate(10, 2, "divide"))
print(safe_calculate(10, 0, "divide"))Expected Output:
5.0 Error: Cannot divide by zero
Study Tips
- ā¢Read the theory content thoroughly before practicing
- ā¢Review the example code to understand key concepts
- ā¢Proceed to the Practice tab when you're ready to code