Exception Handling (Try-Except)
Don't let unexpected errors crash your application. Learn how to gracefully catch and handle exceptions.
Expecting the Unexpected
In the real world, APIs go down, users type letters instead of numbers, and files go missing. If Python hits an error it can't resolve, it raises an Exception and violently crashes the entire program.
The Try-Except Block
You can protect fragile code by wrapping it in a try block. If it fails, the program doesn't crash; instead, it elegantly passes control to the except block.
try:
age = int(input("Enter your age: "))
print(100 / age)
except ValueError:
print("Please enter a valid number, not text!")
except ZeroDivisionError:
print("Age cannot be zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")Finally: The Cleanup Crew
The finally block is executed no matter what happens—whether the try block succeeded or crashed. It is crucial for cleaning up resources, like closing a database connection so it doesn't leak memory.
try:
file = open("data.txt")
# Do risky file operations
finally:
file.close() # This will ALWAYS run