Python Exception Handling
Python Exception Handling
try:
a = int("abc") # This will raise ValueError
b = [1, 2, 3]
print(b[5]) # This will raise IndexError
except (ValueError, IndexError) as e:
print(f"An error occurred: {e}")
try:
file = open("test.txt", "r")
except FileNotFoundError:
print("File not found!")
finally:
print("Execution completed.")
Advantages:
Prevents program crashes – Handles unexpected errors gracefully.
Enhances debugging – Helps identify and handle exceptions properly.
Improves user experience – Provides friendly error messages instead of program termination.
Ensures resource management – Allows proper handling of files, database connections, etc.
Disadvantages:
Overuse can hide bugs – Catching all exceptions might suppress critical errors.
Performance overhead – Handling exceptions is slower than regular code execution.
Complexity – Nested try-except blocks can make code harder to read and maintain.
Python Exception Handling Tutorial