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
In this example, we are dividing two numbers. If the second number is zero, it will cause an error. By using try
and except
, we can handle this error:
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!
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!
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.
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".