Python – Error Handling & Best Practices
Errors are part of every real-world application. A file may be missing, an API may fail, or a user may enter invalid data. Good error handling helps your Python application respond safely instead of crashing unexpectedly.
- Understand Python errors and exceptions.
- Handle failures using
try,except,elseandfinally. - Raise exceptions and create custom exception classes.
- Preserve useful debugging information.
- Apply practical error-handling best practices.
1. What Are Errors and Exceptions in Python?
An error is a problem that prevents code from completing its intended work. Python reports many runtime problems through exceptions. An exception is an object that describes an unusual condition during execution.
Consider an application that reads an order quantity from a user. The user may enter text instead of a number. Python cannot convert that text into an integer, so it raises a ValueError.
quantity = int(input("Enter quantity: "))
print("Quantity:", quantity)
If the user enters five, the program stops with an exception similar to this:
Enter quantity: five ValueError: invalid literal for int() with base 10: 'five'
Python has several built-in exception types. Each one describes a different category of problem.
| Exception | When it occurs |
|---|---|
ValueError |
A value has the wrong format or is outside an expected range. |
TypeError |
An operation receives an unsupported type. |
ZeroDivisionError |
A number is divided by zero. |
IndexError |
A sequence index does not exist. |
KeyError |
A dictionary key does not exist. |
FileNotFoundError |
An expected file cannot be found. |
PermissionError |
The process lacks permission for an operation. |
ImportError |
An import cannot be completed. |
2. Handling Exceptions with try and except
Use try when a block of code may fail. Use except to handle a specific exception and decide what should happen next.
try:
quantity = int(input("Enter quantity: "))
print("Quantity:", quantity)
except ValueError:
print("Please enter a valid whole number.")
Now the application handles invalid input without displaying an unhandled traceback to the user.
Enter quantity: five Please enter a valid whole number.
Handling multiple exception types
One operation may fail for different reasons. We can use separate except blocks to handle each known failure.
try:
first_number = int(input("Enter first number: "))
second_number = int(input("Enter second number: "))
result = first_number / second_number
print("Result:", result)
except ValueError:
print("Enter valid integer values.")
except ZeroDivisionError:
print("The second number cannot be zero.")
Each handler responds to a different problem. This makes the program easier to understand and maintain.
Exception inheritance and handler order
Python exceptions follow an inheritance hierarchy. Some exception classes are more general than others. Place specific handlers before general handlers.
try:
value = int("hello")
except ValueError:
print("The value is not a valid integer.")
except Exception:
print("An unexpected error occurred.")
Exception first makes later specific handlers unreachable for exceptions it already catches. Put broad handlers last.3. Understanding else and finally
Python provides two optional blocks that make exception handling more organised.
elseruns only when thetryblock completes without an exception.finallyruns whether the operation succeeds or raises an exception.
try:
amount = float(input("Enter payment amount: "))
except ValueError:
print("Invalid payment amount.")
else:
print("Payment amount received:", amount)
finally:
print("Payment input process completed.")
For a valid amount, the output looks like this:
Enter payment amount: 1250 Payment amount received: 1250.0 Payment input process completed.
For invalid input, the except block runs instead. The finally block still executes.
Where should we use finally?
Use finally for cleanup that must happen after an operation. Examples include releasing a resource or closing a connection when explicit cleanup is necessary.
file = None
try:
file = open("orders.txt", "r", encoding="utf-8")
content = file.read()
print(content)
except FileNotFoundError:
print("The orders file was not found.")
finally:
if file is not None:
file.close()
print("File closed.")
with statement for normal file operations. It closes the file automatically, even when an exception occurs.4. Raising Exceptions with raise
Sometimes Python does not know that a value is invalid for your business rules. Your application must validate that condition and raise an exception itself.
The raise keyword allows us to signal an error when a condition is not acceptable.
def validate_quantity(quantity):
if quantity <= 0:
raise ValueError("Quantity must be greater than zero.")
return quantity
try:
order_quantity = validate_quantity(-3)
print("Order quantity:", order_quantity)
except ValueError as error:
print("Order rejected:", error)
Order rejected: Quantity must be greater than zero.
This approach keeps validation close to the business rule. The calling code decides how to communicate the failure.
Re-raising an exception
Sometimes a function must record an error but should not hide it. Use raise without an argument inside an exception handler to re-raise the current exception.
def load_order():
try:
with open("order.json", "r", encoding="utf-8") as file:
return file.read()
except FileNotFoundError:
print("Order file is missing.")
raise
try:
load_order()
except FileNotFoundError:
print("The caller must handle the missing order file.")
The original exception continues to the caller. This keeps the failure visible instead of silently pretending the operation succeeded.
5. Creating Custom Exceptions
Built-in exceptions cover common technical failures. Real applications also have business-specific rules. A custom exception gives those failures a clear name.
For example, an order system may reject an order when the requested quantity exceeds available stock.
class InsufficientStockError(Exception):
"""Raised when requested stock is unavailable."""
def place_order(requested_quantity, available_stock):
if requested_quantity > available_stock:
raise InsufficientStockError(
"Not enough stock to complete this order."
)
return "Order placed successfully."
try:
result = place_order(10, 4)
print(result)
except InsufficientStockError as error:
print("Order failed:", error)
Order failed: Not enough stock to complete this order.
Custom exceptions make business failures easier to identify. They also let different application layers handle specific conditions independently.
Exception. Use meaningful names ending in Error.6. How Exception Handling Flows Through a Program
When an exception occurs, Python looks for a matching handler. It first checks the current function. If no matching handler exists, the exception can move to the calling function.
Python exception handling flow
The finally block runs after the try/except/else flow, including when an exception is propagating.
Remember that an exception is not automatically handled just because a try block exists. A matching handler must be available in the current call stack, or the exception remains unhandled.
7. Logging Exceptions for Debugging
Printing an error is useful in small examples. Production applications need better diagnostic information. Python's built-in logging module records messages with severity levels and timestamps.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)
def read_configuration():
try:
with open("config.json", "r", encoding="utf-8") as file:
return file.read()
except FileNotFoundError:
logging.exception("Configuration file could not be loaded.")
raise
try:
read_configuration()
except FileNotFoundError:
print("Application cannot start without configuration.")
logging.exception() records the error message and current exception traceback. Call it from inside an exception handler.
8. Best Practices for Python Error Handling
Good error handling is not about catching every possible exception. It is about handling expected failures at the correct level and preserving enough information to investigate unexpected ones.
| Practice | Recommended approach | Why it matters |
|---|---|---|
| Catch specific exceptions | Catch ValueError or FileNotFoundError when appropriate. |
Avoids hiding unrelated failures. |
| Keep try blocks focused | Wrap only operations that may raise the exception you expect. | Makes the source of failure clear. |
| Do not ignore errors | Log, handle, or re-raise the exception. | Prevents silent data or workflow failures. |
| Use custom exceptions | Create meaningful business exception types. | Separates business failures from technical failures. |
| Preserve context | Use exception chaining with raise ... from error. |
Keeps the original cause available. |
| Clean up resources | Prefer with for files and supported resources. |
Reduces resource leaks. |
| Log useful details | Use structured logging and traceback information. | Helps diagnose production issues. |
Avoid these common mistakes
try:
process_payment()
except:
pass
This code hides every failure. The caller cannot tell whether payment processing succeeded or failed.
try:
process_payment()
except ConnectionError:
print("Payment service is temporarily unavailable.")
except TimeoutError:
print("Payment request timed out.")
9. Exception Chaining and Preserving the Original Cause
Sometimes a low-level exception needs a more useful application-level message. Python supports exception chaining with raise ... from ....
class ConfigurationLoadError(Exception):
pass
def load_settings():
try:
with open("settings.json", "r", encoding="utf-8") as file:
return file.read()
except FileNotFoundError as error:
raise ConfigurationLoadError(
"Required application settings are missing."
) from error
try:
load_settings()
except ConfigurationLoadError as error:
print("Startup error:", error)
The caller sees a meaningful application error. The original FileNotFoundError remains available as the cause in the traceback.
Use exception chaining when translating an error between application layers. Avoid replacing the original cause with an unrelated message.
10. Real-World Example – Handling an Order Workflow
Consider an online store that accepts customer orders. It must validate the quantity, check stock, and create an order. Each step can fail for a different reason.
The following example combines validation, custom exceptions, specific handlers and logging.
import logging
logging.basicConfig(level=logging.INFO)
class InvalidQuantityError(Exception):
pass
class InsufficientStockError(Exception):
pass
def create_order(quantity, available_stock):
if quantity <= 0:
raise InvalidQuantityError(
"Order quantity must be greater than zero."
)
if quantity > available_stock:
raise InsufficientStockError(
"Requested quantity is not available."
)
return {
"order_id": 501,
"quantity": quantity,
"status": "Confirmed"
}
def main():
try:
order = create_order(
quantity=5,
available_stock=3
)
except InvalidQuantityError as error:
logging.warning("Order validation failed: %s", error)
except InsufficientStockError as error:
logging.warning("Stock validation failed: %s", error)
else:
logging.info("Order created: %s", order)
print("Order successful:", order)
finally:
print("Order processing completed.")
if __name__ == "__main__":
main()
Run the example using a Python terminal:
python order_processing.py
Expected output for the supplied values:
WARNING:root:Stock validation failed: Requested quantity is not available. Order processing completed.
The order is rejected because the requested quantity exceeds available stock. The application records the reason instead of crashing silently.
11. Quick Interview Questions
try contains code that may fail. except handles a matching exception.else runs only when the try block succeeds. finally runs after the handling flow regardless of success or failure.raise NewError() from error.logging.exception() also includes exception traceback information when called inside an exception handler.12. Hands-On Practice
with. Handle a missing file and print a useful message.InsufficientBalanceError. Raise it when a withdrawal exceeds the account balance.Conclusion
Error handling is an essential part of reliable Python development. Use specific exceptions, keep protected code focused, and preserve useful debugging information. Use custom exceptions for business rules and logging for operational visibility.
Most importantly, never hide a failure just to keep an application running. Handle it deliberately, communicate the correct result, and leave enough context for developers to investigate it.
Good Python error handling makes applications predictable, maintainable and easier to debug. Catch what you understand, raise what you cannot accept, and log what needs investigation.
Upgradix by Shrash Studio — Learn Technology. Build Your Future.