Exception Handling
Exception Handling
Multiple Exceptions
Python allows handling multiple exceptions in a single except block by specifying a tuple
of exception types:
try:
value = int(input("Enter a number: "))
result = 10 / value
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
Here, both ValueError (from invalid input) and ZeroDivisionError are handled, providing a
more user-friendly experience.
Common Exceptions
Some common exceptions in Python include:
• TypeError: Raised when an operation or function is applied to an object of
inappropriate type.
• IndexError: Raised when trying to access an index that is out of range for a list
or tuple.
• KeyError: Raised when trying to access a dictionary with a key that does not
exist.
Best Practices
1. Be Specific: Catch specific exceptions instead of a general Exception, which can
obscure the source of errors.
2. Use Finally for Cleanup: Always use the finally clause for cleanup tasks to
ensure resources are properly released.
3. Log Exceptions: Implement logging to keep track of exceptions that occur,
aiding in debugging and maintenance.
By implementing effective exception handling, Python developers can create more
resilient applications, reducing the likelihood of crashes and enhancing user experience.