Introduction
Even well-written Python code can run into unexpected issues. Files might not exist, input could be invalid, or network connections may fail. Rather than crashing your program, Python provides a way to handle these situations gracefully using try
, except
, and finally
. This article walks through the basics of error handling in Python.
Basic try and except
The simplest form of error handling wraps code in a try
block and catches exceptions with except
:
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("That was not a valid number.")
except ZeroDivisionError:
print("You can't divide by zero.")
You can catch specific exceptions to handle different problems differently.
Using finally
The finally
block runs no matter what—whether an error occurred or not. It’s useful for cleanup tasks like closing files or network connections:
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
Generic Exception Handling
You can catch any kind of exception using a generic except Exception as e
pattern:
try:
risky_operation()
except Exception as e:
print("An error occurred:", e)
This approach helps when you’re debugging or when you want to log errors but not crash.
Why Not Ignore Errors?
It’s tempting to write a blank except:
block to avoid program crashes. However, this can hide bugs and make debugging harder. Always catch specific exceptions or log unexpected ones clearly.
Conclusion
By mastering try
, except
, and finally
, you can prevent your Python programs from crashing and make them more reliable. Handle specific exceptions where possible and use finally
to clean up resources safely.
Comment