Python Error Handling: Using Try and Except
In this seventh article of our beginner-friendly Python tutorial series, we'll explore error handling in Python using try and except statements. Proper error handling is crucial for writing robust and resilient code, as it allows you to gracefully handle unexpected situations and prevent your program from crashing.
Handling Exceptions with Try and Except
Exceptions are events that occur during the execution of a program when an error is encountered. To handle exceptions, you can use try and except statements. The code inside the try block is executed, and if an exception occurs, the code inside the except block is executed.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
print("An error occurred: division by zero.")
Catching Multiple Exceptions
You can catch multiple exceptions by specifying them as a tuple in the except clause. Here's an example:
try:
# Code that might raise an exception
result = 10 / "2"
except (ZeroDivisionError, TypeError):
print("An error occurred: either division by zero or an invalid operand.")
Getting Exception Information
You can get more information about an exception by using the `as` keyword to assign the exception to a variable. Here's an example:
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
print(f"An error occurred: {e}")
Using Else and Finally Clauses
You can use the `else` clause to specify a block of code that will be executed if no exception is raised in the try block. The `finally` clause is used to specify a block of code that will always be executed, regardless of whether an exception is raised or not. Here's an example:
try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError:
print("An error occurred: division by zero.")
else:
print("No exception occurred.")
finally:
print("This block will always be executed.")
Creating Custom Exceptions
You can create custom exceptions by defining a new class that inherits from the built-in `Exception` class. This allows you to handle specific error conditions in your code more effectively. Here's an example:
class MyCustomException(Exception):
pass
try:
# Code that might raise a custom exception
raise MyCustomException("This is a custom exception.")
except MyCustomException as e:
print(f"An error occurred: {e}")
Raising Exceptions
Sometimes, you may want to raise an exception in your code intentionally. You can do this using the `raise` keyword, followed by the exception class or an instance of the exception class. Here's an example:
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
try:
# Code that might raise an exception
validate_age(-5)
except ValueError as e:
print(f"An error occurred: {e}")
Now that you've learned about error handling in Python, you can write more robust and resilient code that can handle unexpected situations gracefully. This skill is essential for writing real-world applications and scripts. In the next article, we'll explore data structures in Python, which will help you organize and manipulate data in your programs. Stay tuned!