Exception Handling
Exception handling is a mechanism in Python that allows you to gracefully handle errors that may occur during program execution. It helps prevent your program from crashing and provides a way to recover from unexpected situations.
The try-except Block:
The try-except block is the fundamental construct for exception handling in Python. It consists of a try block, where the code that might raise an exception is placed, and one or more except blocks to handle specific exceptions.
Python
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Common Exceptions:
- ZeroDivisionError: Raised when dividing by zero.
- TypeError: Raised when an operation is performed on an object of an inappropriate type.
- ValueError: Raised when a built-in operation or function receives an argument of an inappropriate type or value.
- IndexError: Raised when an index is out of range for a list, tuple, or string.
- KeyError: Raised when a dictionary key is not found.
- FileNotFoundError: Raised when a file is not found.
Example:
Python
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter numbers.")
Best Practices:
- Use specific exception types to catch only the exceptions you expect.
- Provide informative error messages.
- Consider using try-except-finally blocks to ensure that cleanup code is always executed.
- Avoid excessive use of except blocks, as it can make your code harder to debug.
Additional Considerations:
- Custom Exceptions: You can create custom exceptions by defining new classes that inherit from the Exception class.
- Raising Exceptions: Use the raise keyword to raise exceptions manually.
- Context Managers: The with statement can be used to manage resources and automatically handle exceptions.
By understanding and effectively using exception handling in Python, you can write more robust and resilient programs.