An error is a problem that occurs when running your program, while an exception is a special type of error that you can catch and handle in your program. Errors can occur for various reasons, like wrong input or trying to divide by zero.
For example:
- Trying to divide a number by zero.
- Trying to access a file that doesn’t exist.
- Trying to use a variable that hasn’t been defined.
How to handle errors in Python
Python provides a way to handle errors using try, except, else, and finally blocks. This approach helps you handle errors gracefully and continue your program without crashing.
The try block
The try
try
except
block.
try:
# Code that might cause an error
result = 10 / 0 # Division by zero
except ZeroDivisionError:
# Handling the error
print("You can't divide by zero!")
The except block
The except
ZeroDivisionError
The else block
The else
try
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful:", result)
The finally block
The finally
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the file.")
file.close() # Ensures the file is closed even if an error occurred
Raising Exceptions
Sometimes, you may want to raise your own exceptions if something goes wrong in your program. You can do this using the raise
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
else:
print("Your age is:", age)
try:
check_age(-5)
except ValueError as e:
print("Error:", e)
Common Python Exceptions
Here are some common exceptions you might encounter in Python:
- ZeroDivisionError: Occurs when trying to divide by zero.
- FileNotFoundError: Raised when trying to open a file that doesn't exist.
- ValueError: Raised when a function receives an argument of the correct type, but an inappropriate value.
- IndexError: Raised when trying to access an index that is out of range in a list.
Recap
- Use the
block for code that may cause an error.try
- Use the
block to catch and handle exceptions.except
- Use the
block for code that should run if no error occurs.else
- Use the
block for cleanup tasks.finally
- Raise your own exceptions using
when necessary.raise