Python Error Handling
What is Error Handling in Python?
Error handling in Python lets you gracefully handle unexpected errors during runtime without crashing the program.
Basic Syntax of try, except
try:
# Code that may raise an exception
risky_code()
except ExceptionType:
# Code to run if an exception occurs
handle_error()
Example: Basic try-except
try:
number = int(input("Enter a number: "))
print(10 / number)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input, enter a number.")
Possible Outputs:
Enter a number: 0 Cannot divide by zero! Enter a number: abc Invalid input, enter a number.
Catch All Exceptions
try:
result = 10 / 0
except Exception as e:
print("An error occurred:", e)
Output:
An error occurred: division by zero
Use this with caution - it hides specific error types.
finally Block in Python
The finally block runs no matter what, whether an exception is raised or not.
Example:
try:
file = open("test.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Execution complete.")
Output:
File not found! Execution complete.
Using else with try-except
The else block runs only if no exception was raised.
try:
print("No errors here!")
except:
print("Something went wrong.")
else:
print("Code ran successfully!")
Common Exception Types in Python
Exception | Description |
---|---|
ZeroDivisionError | Division by zero error |
ValueError | Wrong data type |
FileNotFoundError | File not found |
TypeError | Invalid operation between types |
IndexError | List index out of range |
Best Practices for Python Exception Handling
- Catch specific exceptions (not just Exception)
- Use finally to close resources (e.g., files, DB connections)
- Avoid bare except: unless absolutely necessary
- Log exceptions for debugging in production apps