Python try-except Tutorial: Mastering Error Handling
Last updated 5 months, 1 week ago | 347 views 75 5

Errors are inevitable in programming. But with Python’s try
-except
blocks, you can gracefully handle exceptions and make your programs more robust, user-friendly, and crash-resistant.
This guide explains:
-
What exceptions are
-
How
try
-except
works -
Common exception types
-
Advanced usage (
else
,finally
) -
Real-world examples
-
Tips and common pitfalls
What Is an Exception?
An exception is an error that occurs during the execution of a program, disrupting its normal flow.
Example:
print(10 / 0)
Output:
ZeroDivisionError: division by zero
This stops the program. But what if we could handle it smoothly?
Basic Syntax of try
-except
try:
# Code that might throw an error
except SomeException:
# Code to run if an error occurs
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
You can't divide by zero!
Catching Multiple Exceptions
You can handle multiple specific exceptions:
try:
value = int("abc")
except ValueError:
print("Invalid input: not an integer")
Or handle several at once:
try:
risky_code()
except (ValueError, ZeroDivisionError):
print("Something went wrong with input or math.")
Catching All Exceptions (Use with Caution)
try:
unknown_function()
except Exception as e:
print(f"An error occurred: {e}")
-
✅ Good for logging or debugging
-
⚠️ Not recommended for silent failure or production masking
✅ Using else
with try
The else
block runs only if no exception was raised.
try:
number = int("42")
except ValueError:
print("Conversion failed")
else:
print("Conversion successful:", number)
Using finally
for Cleanup
The finally
block always executes, whether or not an exception occurred. It’s useful for resource cleanup like closing files or database connections.
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file (if open)")
if 'file' in locals():
file.close()
Common Python Exceptions
Exception | Raised When... |
---|---|
ZeroDivisionError |
You divide by zero |
ValueError |
A function gets an argument of the right type but wrong value |
TypeError |
Wrong data type used |
IndexError |
List index out of range |
KeyError |
Dictionary key not found |
FileNotFoundError |
File operation fails because the file doesn't exist |
AttributeError |
You call an attribute that doesn’t exist |
Real-World Example: Safe Input and Division
def safe_divide():
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
except ValueError:
print("Please enter valid integers.")
except ZeroDivisionError:
print("Denominator cannot be zero.")
else:
print(f"Result: {result}")
finally:
print("Operation complete.")
safe_divide()
⚠️ Common Pitfalls
Pitfall | Explanation | Solution |
---|---|---|
Catching everything blindly | Masks bugs | Catch specific exceptions where possible |
Silent except: blocks |
Fail silently | Always log or inform the user |
Not using finally for cleanup |
May leave open resources | Use finally to release files, connections, etc. |
Too much logic in try block |
Hard to debug | Keep try block small and focused |
Tips
✅ Use try
-except
to handle expected errors (e.g., user input, file access)
✅ Always catch specific exceptions first, then general ones
✅ Log errors during development or in production environments
✅ Use else
for code that should only run if no error occurred
✅ Use finally
for guaranteed clean-up, even if an exception occurs
Complete Code Example
def process_file(filename):
try:
file = open(filename, "r")
content = file.read()
except FileNotFoundError:
print(f"Error: File '{filename}' does not exist.")
except PermissionError:
print(f"Error: Permission denied for file '{filename}'.")
else:
print("File read successfully:")
print(content)
finally:
if 'file' in locals():
file.close()
print("File closed.")
# Try with an existing and a non-existing file
process_file("example.txt")
Conclusion
Python’s try
-except
blocks are essential for writing reliable code. By anticipating errors and handling them appropriately, you can make your applications more robust, user-friendly, and maintainable.
Learn to use try
, except
, else
, and finally
strategically, and you’ll have the tools to handle almost anything Python throws at you.