Exception Handling in Python
Introduction
In Python, exception handling is a critical mechanism that allows developers to manage errors and other exceptional conditions gracefully. It enables the program to continue executing, instead of terminating abruptly. This lesson covers the fundamentals of exception handling in Python.
Key Concepts
- Exception: An event that disrupts the normal flow of a program.
- Raising an Exception: Signaling that an error has occurred.
- Handling an Exception: Using try-except blocks to catch and manage exceptions.
- Finally Clause: Code that runs regardless of whether an exception occurred.
- Custom Exceptions: User-defined exceptions that can be raised for specific errors.
Try-Except Blocks
The basic structure for handling exceptions in Python is the try-except block. Here’s how it works:
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
In this example, attempting to divide by zero raises a ZeroDivisionError
, which is caught and handled gracefully.
Finally and Else Clauses
The finally
clause is executed no matter what, while the else
clause runs if the try block succeeds without exceptions:
try:
result = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print(f"Result: {result}")
finally:
print("Execution finished.")
This code will output the result and the final message since no exception occurs.
Raising Exceptions
You can raise exceptions manually using the raise
statement:
def check_value(x):
if x < 0:
raise ValueError("Negative value provided!")
try:
check_value(-1)
except ValueError as e:
print(e)
This function raises a ValueError
if a negative value is passed.
Custom Exceptions
You can define your own exceptions by extending the base Exception
class:
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)
This code demonstrates how to create and raise a custom exception.
Best Practices
- Use specific exceptions rather than a generic one.
- Always clean up resources in a
finally
block. - Log exceptions instead of just printing them.
- Define custom exceptions for better clarity.
- Keep your exception handling code clean and concise.
FAQ
What is an exception in Python?
An exception is an error that occurs during the execution of a program, disrupting the normal flow of instructions.
How do I catch multiple exceptions?
You can catch multiple exceptions by using a tuple in the except statement:
try:
# some code
except (TypeError, ValueError) as e:
print(f"Error: {e}")
Can I use else and finally together?
Yes, you can use both else
and finally
in a try-except block. The else
block runs if no exceptions occur, while finally
runs regardless.