Errors and try-except
Errors are common when writing code. Python provides a way to handle them gracefully using the try-except
block.
This lesson will introduce different types of errors and how to handle them.
Common Types of Errors in Python
-
SyntaxError – Occurs when the code has incorrect syntax.
print("Hello, World! # Missing closing quote
Error:
SyntaxError: EOL while scanning string literal
-
NameError – Occurs when trying to use a variable that hasn't been defined.
print(age) # age is not defined
Error:
NameError: name 'age' is not defined
-
TypeError – Happens when an operation is performed on incompatible types.
print("5" + 5) # Cannot add a string and an integer
Error:
TypeError: can only concatenate str (not "int") to str
-
IndexError – Raised when trying to access an index that doesn’t exist.
my_list = [1, 2, 3] print(my_list[5]) # Index out of range
Error:
IndexError: list index out of range
-
KeyError – Raised when accessing a non-existent key in a dictionary.
my_dict = {"name": "Alice"} print(my_dict["age"]) # 'age' key does not exist
Error:
KeyError: 'age'
Handling Errors with try-except
We can use try-except
to handle errors and prevent the program from crashing.
Example: Handling Division by Zero
try:
result = 10 / 0 # This will cause an error
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
You can't divide by zero!
Example: Handling Multiple Errors
try:
x = int("Hello") # This will raise a ValueError
except (ValueError, TypeError):
print("Oops! Something went wrong.")
Output:
Oops! Something went wrong.
Example: Catching Any Error with Exception
try:
print(10 / 0)
except Exception as e:
print("An error occurred:", e)
Output:
An error occurred: division by zero
Exercise: Try It Yourself!
- Create a list and try to access an index that doesn’t exist. Handle the error properly.
- Try converting a string into an integer using
int("Hello")
. Catch theValueError
. - Write a program that asks the user to input two numbers and divides them, handling any errors.