Error handling in Python helps make programs more reliable by letting us manage errors when they occur. Using try/except blocks and assertions, we can prevent programs from crashing unexpectedly.
Error Handling in Python
1. The try/except Block
The try
and except
keywords help us catch and handle errors in Python. By putting code that might cause an error inside a try
block, we can catch specific errors in the except
block.
Example
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Explanation: If dividing by zero causes an error, Python will skip the rest of the try
block and run the except
block, printing Cannot divide by zero!
try/except Quiz
What happens if an error occurs in a try block?
What's the purpose of specifying ZeroDivisionError in the except clause?
2. Catching Different Errors
We can handle multiple errors by using different except
blocks for each error type.
Example
try:
my_list = [1, 2, 3]
print(my_list[5]) # IndexError
except IndexError:
print("Index is out of range!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Explanation: Here, we handle both IndexError
and ZeroDivisionError
. If we try to access an index that doesn't exist, it will print Index is out of range!
Multiple Errors Quiz
What happens if an error occurs that doesn't match any except blocks?
How can you catch all possible exceptions?
3. The else and finally Blocks
The else
block runs only if no errors occur, while finally
runs no matter what.
Example
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
finally:
print("This will always run.")
Explanation: else
runs if there is no error. finally
runs whether or not an error occurred, often used for cleanup tasks.
else/finally Quiz
When does the else block execute?
What is the most common use of the finally block?
4. Using Assertions
assert
is used to test conditions and stop the program if the condition is False. It is helpful for debugging by ensuring assumptions are correct.
Example
def get_positive_number(num):
assert num > 0, "Number must be positive"
return num
print(get_positive_number(5)) # Works fine
print(get_positive_number(-2)) # Raises AssertionError
Explanation: If num
is not positive, assert
will raise an AssertionError
with the message "Number must be positive".
Assertions Quiz
What happens when an assert condition is False?
When should you use assert statements?