🚫 Python Errors and Exception Handling – try, except, raise, finally, and Logging
Master Safe and Reliable Error Management in Python
🧲 Introduction – Why Error Handling Matters?
In programming, things can go wrong — files may be missing, APIs may return bad data, or users may enter unexpected input. Python provides a robust exception-handling mechanism to gracefully handle such issues without crashing your application.
🎯 In this guide, you’ll learn:
- Difference between errors and exceptions
- How to use try…except and try…finally blocks
- How to raise, chain, and define custom exceptions
- Logging and asserting errors for better debugging
📌 Topics Covered
⚙️ Topic | 📝 Description |
---|---|
Python Errors vs. Exceptions | Understand the distinction between syntax errors and runtime exceptions |
Python try…except Block | Catch and handle exceptions using try/except syntax |
Python try…finally Block | Ensure important cleanup happens regardless of exceptions |
Python Raising Exceptions | Use raise to trigger exceptions deliberately |
Python Exception Chaining | Link multiple exceptions using raise ... from |
Python Nested try Block | Use multiple try blocks inside one another safely |
Python User-defined Exceptions | Define custom exceptions for your application logic |
Python Built-in Exceptions | Use Python’s library of standard exceptions |
Python Logging | Log exceptions to file or console using the logging module |
Python Assertions | Use assert for quick checks in testing and debugging |
🧱 Python Errors vs. Exceptions
- Errors: Problems in the syntax of the code (e.g., missing colons, incorrect indentation).
- Exceptions: Runtime anomalies that occur during execution (e.g., division by zero, file not found).
# Syntax Error Example (compile-time)
if True
print("Missing colon")
# Exception Example (runtime)
print(10 / 0) # ZeroDivisionError
🧪 Python try…except
Block
Used to catch and handle exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
✅ Explanation:
- The code inside
try
runs first. - If an error occurs, control moves to
except
.
🔐 Python try…finally
Block
The finally
block always executes, whether or not an exception occurred.
try:
f = open("demo.txt")
finally:
f.close()
print("File closed.")
✅ Use Case: Closing resources like files or network connections.
🚨 Python Raising Exceptions
Use raise
to trigger an error manually.
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
✅ Helpful for validating function arguments or enforcing rules.
🔗 Python Exception Chaining
Use raise ... from ...
to indicate the original cause of an exception.
try:
int("abc")
except ValueError as e:
raise RuntimeError("Conversion failed") from e
✅ Helps trace errors back to the root cause.
🧩 Python Nested try
Block
You can place one try
block inside another.
try:
try:
x = int("a")
except ValueError:
print("Inner block handled ValueError")
except:
print("Outer block")
✅ Useful when different types of exceptions need to be handled at different levels.
🛠️ Python User-defined Exceptions
Create your own exception class by inheriting from Exception
.
class NegativeAgeError(Exception):
pass
def validate_age(age):
if age < 0:
raise NegativeAgeError("Age must be positive.")
✅ Helps enforce domain-specific rules.
📚 Python Built-in Exceptions
Exception | Description |
---|---|
ZeroDivisionError | Division by zero |
ValueError | Invalid value |
TypeError | Mismatched data types |
FileNotFoundError | File doesn’t exist |
IndexError | Index out of bounds |
KeyError | Dictionary key not found |
🧾 Python Logging
Use the logging
module to record errors.
import logging
logging.basicConfig(level=logging.ERROR)
try:
x = 1 / 0
except ZeroDivisionError as e:
logging.error("An error occurred", exc_info=True)
✅ Preferred over print statements for production debugging.
🧷 Python Assertions
Use assert
for quick checks during development.
x = 10
assert x > 0, "x must be positive"
✅ Automatically raises an AssertionError
if the condition fails. Useful for debugging and testing.
📌 Summary – Recap & Next Steps
Python’s exception handling system is both powerful and flexible. It helps you build safe, fault-tolerant applications by catching, raising, and managing errors gracefully.
🔍 Key Takeaways:
- Use
try…except
to catch exceptions. - Use
finally
to release resources like files. - Raise custom errors using
raise
, and create your own with custom classes. - Use the
logging
module for better error reporting. - Use
assert
for validation and debugging.
⚙️ Real-World Relevance:
Exception handling is used in API integrations, file operations, user input validation, and system-level operations across nearly every Python application.
❓ FAQ – Python Error Handling
❓ What’s the difference between an error and an exception?
✅ Errors are syntax-level problems; exceptions happen during execution.
❓ What is the benefit of using finally
?
✅ It guarantees execution of cleanup code (e.g., closing files).
❓ How do I define a custom exception?
class MyError(Exception):
pass
❓ Should I use logging instead of print()?
✅ Yes. Logging allows severity levels, formatting, and persistence.
❓ Is assert
used in production code?
❌ It’s typically used in testing and debugging — not for end-user error handling.
Share Now :