- Learning Objectives
- Prerequisites
- Introduction
- Why Best Practices are Important
- Best Practices for Exception Handling
- Common Anti-Patterns
- Exception Logging
- Resource Management
- Production-Ready Exception Handling
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Write clean exception handling code.
- Follow Python's recommended exception handling practices.
- Avoid common exception handling mistakes.
- Understand when and where to catch exceptions.
- Learn basic exception logging.
- Write production-ready Python programs.
Before learning this chapter, you should know:
- Exception Handling
- try-except Blocks
- else Block
- finally Block
- raise Keyword
- User-Defined Exceptions
Exception Handling is one of the most important aspects of software development.
Handling exceptions incorrectly can make programs:
- Difficult to debug
- Difficult to maintain
- Less secure
- Unreliable
Good exception handling makes applications:
- Stable
- Readable
- Maintainable
- User-friendly
Python provides powerful exception handling features,
but they should be used correctly.
Suppose a Banking Application catches every exception like this:
try:
withdraw()
except:
passIf a serious error occurs,
the program silently ignores it.
The developer has no idea what went wrong.
Instead,
exceptions should be handled carefully,
logged when appropriate,
and meaningful messages should be displayed.
Following these practices leads to cleaner and more reliable code.
Always catch the most specific exception possible.
✅ Good
except ValueError:
print("Invalid input.")❌ Bad
except:
print("Error")Specific exception handling makes debugging easier.
Only include statements that may actually raise exceptions.
✅ Good
try:
number = int(input())
except ValueError:
print("Invalid Number")Avoid placing unrelated code inside the try block.
Bad messages make debugging difficult.
❌ Poor
Error
✅ Better
Age must be greater than or equal to 18.
Avoid writing
except:
passunless there is a valid reason.
Ignoring exceptions makes debugging difficult.
Resources should always be released.
Examples include:
- Files
- Database Connections
- Network Connections
Use
finallyto ensure cleanup.
Use
raiseto enforce business rules.
Example
raise ValueError("Invalid Age")When built-in exceptions are not descriptive enough,
create custom exceptions.
Example
class InsufficientBalanceError(Exception):
passInstead of hiding errors,
record them.
Example
import logging
logging.error("Database Connection Failed")Logging helps developers diagnose problems later.
Always validate user input.
Example
if age < 18:
raise ValueError("Invalid Age")Keep validation and exception handling independent from the main business logic.
This improves readability and maintainability.
Avoid the following practices.
except:Avoid this unless absolutely necessary.
except:
passThis hides errors.
Exceptions should represent exceptional situations,
not normal program behavior.
Prefer
ValueErrorinstead of
Exceptionwhenever possible.
Always release resources using
finallyor a context manager (with statement).
In production applications,
errors should be logged.
Example
import logging
logging.basicConfig(level=logging.ERROR)
try:
print(10 / 0)
except ZeroDivisionError:
logging.exception("Division Error")Logging stores useful debugging information,
including the traceback.
Good
file = None
try:
file = open("sample.txt")
finally:
if file:
file.close()Even better,
use Python's
withstatement,
which automatically closes the file.
with open("sample.txt") as file:
print(file.read())A production-ready application should:
- Catch specific exceptions.
- Log unexpected errors.
- Display user-friendly messages.
- Avoid exposing internal implementation details.
- Release resources correctly.
- Validate all external input.
- Use custom exceptions for business rules.
Program Starts
↓
Input Validation
↓
Business Logic
↓
Exception Occurs?
↓
No
↓
Continue Program
------------------------
Yes
↓
Specific Exception Raised
↓
Matching Handler
↓
Log Exception
↓
Cleanup Resources
↓
Continue / Exit Program
- Cleaner code.
- Easier debugging.
- Better maintainability.
- Improved application stability.
- Better user experience.
- Easier production support.
Specific exceptions make debugging easier and prevent unrelated errors from being hidden.
Small try blocks make it easier to identify which statement caused the exception.
Logging records exception details for debugging and production monitoring.
Because it silently hides errors and makes debugging difficult.
It ensures that resources are released regardless of whether an exception occurs.
- Catch specific exceptions.
- Keep try blocks small.
- Use meaningful messages.
- Avoid empty except blocks.
- Use finally for cleanup.
- Log important exceptions.
- Validate inputs.
- Use custom exceptions when needed.
In this chapter, we learned:
- Exception Handling Best Practices
- Exception Logging
- Resource Management
- Common Anti-Patterns
- Production-Ready Exception Handling
- Internal Working
- Interview Questions
- Quick Revision
Write a Python program to catch a specific exception instead of using a generic exception.
try:
number = int(input("Enter Number : "))
except ValueError:
print("Please enter a valid integer.")Enter Number : abc
Please enter a valid integer.
Catching a specific exception makes debugging easier and prevents unrelated exceptions from being hidden.
name = input("Enter Name : ")
try:
age = int(input("Enter Age : "))
except ValueError:
print("Invalid Age")
print("Name :", name)Only the risky statement is placed inside the try block.
The remaining code is kept outside.
try:
marks = int(input("Enter Marks : "))
if marks < 0 or marks > 100:
raise ValueError(
"Marks must be between 0 and 100."
)
except ValueError as error:
print(error)Enter Marks : 120
Marks must be between 0 and 100.
Meaningful error messages help users understand the exact problem.
file = None
try:
file = open("sample.txt")
print("File Opened")
except FileNotFoundError:
print("File Not Found")
finally:
if file:
file.close()
print("File Closed")The finally block ensures that the file is closed if it was successfully opened.
try:
with open("sample.txt") as file:
print(file.read())
except FileNotFoundError:
print("File Not Found")The with statement automatically closes the file.
It is generally preferred over manually calling close().
import logging
logging.basicConfig(level=logging.ERROR)
try:
print(100 / 0)
except ZeroDivisionError:
logging.exception("Division Error")ERROR:root:Division Error
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
Logging stores detailed error information, including the traceback.
This is useful for debugging production applications.
age = int(input("Enter Age : "))
if age < 18:
raise ValueError(
"Age must be at least 18."
)
print("Registration Successful")Enter Age : 15
ValueError: Age must be at least 18.
Input is validated before further processing.
class InvalidSalaryError(Exception):
pass
salary = int(input("Enter Salary : "))
if salary < 0:
raise InvalidSalaryError(
"Salary cannot be negative."
)Enter Salary : -1000
InvalidSalaryError:
Salary cannot be negative.
Custom exceptions improve code readability by representing business rules.
try:
print(100 / 0)
except:
passThis is not recommended.
The exception is silently ignored,
making debugging difficult.
try:
print(100 / 0)
except ZeroDivisionError as error:
print(error)import logging
logging.basicConfig(level=logging.ERROR)
try:
amount = int(input("Enter Amount : "))
if amount <= 0:
raise ValueError(
"Amount must be greater than zero."
)
print("Transaction Successful")
except ValueError as error:
logging.error(error)
print("Invalid Transaction")
finally:
print("Transaction Completed")Enter Amount : -500
Invalid Transaction
Transaction Completed
This example demonstrates:
- Input Validation
- Specific Exception Handling
- Logging
- Cleanup using
finally
These are common practices in production applications.
Program Starts
↓
Input Accepted
↓
Validation
↓
Valid?
↓
Yes
↓
Business Logic
↓
Program Ends
------------------------
No
↓
Raise Exception
↓
Specific except
↓
Log Error
↓
Cleanup
↓
Program Ends
Program
↓
Input
↓
Validation
↓
Exception?
↓
No
↓
Continue
------------------------
Yes
↓
Exception Object
↓
Specific Handler
↓
Logging
↓
finally
↓
Program Ends
- Improves reliability.
- Simplifies debugging.
- Prevents resource leaks.
- Produces maintainable code.
- Improves user experience.
- Supports enterprise application development.
✅ Catch specific exceptions.
✅ Keep try blocks small.
✅ Validate input before processing.
✅ Use meaningful exception messages.
✅ Log unexpected exceptions.
✅ Release resources properly.
✅ Use with for file handling whenever possible.
✅ Create custom exceptions for business rules.
❌ Using
except:for every exception.
❌ Ignoring exceptions using
pass❌ Raising generic exceptions.
❌ Writing large try blocks.
❌ Forgetting to close files.
Specific exception handling makes programs easier to debug and prevents unrelated exceptions from being hidden.
Because they make it difficult to identify which statement caused the exception.
Logging preserves detailed error information for debugging and production monitoring.
The with statement because it automatically releases the resource.
Because they may hide unexpected programming errors.
They help users and developers understand the actual problem.
When business rules cannot be represented clearly using built-in exceptions.
- Catch only
ValueError. - Log a
ZeroDivisionError. - Read a file using the
withstatement. - Validate salary using a custom exception.
- Compare poor and good exception handling.
- Catch specific exceptions.
- Keep try blocks small.
- Validate inputs.
- Use meaningful error messages.
- Log important exceptions.
- Use
finallyfor cleanup. - Prefer
withfor file handling. - Use custom exceptions for business rules.
In this chapter, you learned:
- Exception Handling Best Practices
- Exception Logging
- Resource Management
- Using
withStatement - Production-Ready Exception Handling
- Practical Programs
- Best Practices Checklist
- Common Anti-Patterns
- Interview Questions
- Practice Programs
- Quick Revision