LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Python

Python - Error Handling & Best Practices

In production systems, runtime failures like missing files, network drops, and invalid user inputs are inevitable. Without proper handling, an unhandled error abruptly halts your program with an ugly traceback. By mastering try-except-finally blocks, defining domain-specific custom exceptions, verifying internal invariants with assert, and capturing diagnostics via Python standard logging module, your software gracefully recovers from unexpected failures.

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.

What you will learn
  • Understand Python errors and exceptions.
  • Handle failures using try, except, else and finally.
  • 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.

Python – An unhandled exception
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.
Important distinction: Syntax errors happen when Python cannot parse your code. Exceptions usually occur while valid code is running. Both need attention, but they are handled differently.

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.

Python – Handling invalid user input
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.

Python – Multiple except blocks
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.

Python – Specific exception before general exception
try:
    value = int("hello")

except ValueError:
    print("The value is not a valid integer.")

except Exception:
    print("An unexpected error occurred.")
Common mistake: Catching 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.

  • else runs only when the try block completes without an exception.
  • finally runs whether the operation succeeds or raises an exception.
Python – try, except, else and finally
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.

Python – Cleanup with finally
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.")
Better option for files: Prefer the 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.

Python – Validate an order quantity
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.

Python – Re-raise after recording context
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.

Python – Custom exception for stock validation
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.

Best practice: Derive application-specific exceptions from 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

Start operation Execute try block No exception Run else block Exception raised Find matching except Run finally block

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.

Python – Logging an exception with traceback
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.

Production tip: Avoid logging passwords, access tokens, payment details or personal information. Log enough context to investigate the failure without exposing sensitive data.

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

Avoid – Catching every exception and ignoring it
try:
    process_payment()

except:
    pass

This code hides every failure. The caller cannot tell whether payment processing succeeded or failed.

Better – Handle expected failures explicitly
try:
    process_payment()

except ConnectionError:
    print("Payment service is temporarily unavailable.")

except TimeoutError:
    print("Payment request timed out.")
Important: Do not use a broad handler to make a failed operation appear successful. If you catch an unexpected exception at an application boundary, log it and return an appropriate failure response.

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 ....

Python – Raise a meaningful application exception
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.

Python – Complete order processing example
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:

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.

Real production consideration: A real payment and order workflow needs transaction boundaries, idempotency, retry policies and reliable stock updates. Exception handling alone does not guarantee that distributed operations remain consistent.

11. Quick Interview Questions

1. What is the difference between an error and an exception? An error is a general problem. An exception is a Python object raised to report a condition during execution. Syntax errors are detected while parsing code.
2. What is the purpose of try and except? try contains code that may fail. except handles a matching exception.
3. What is the difference between else and finally? else runs only when the try block succeeds. finally runs after the handling flow regardless of success or failure.
4. Why should we avoid a bare except? It can catch unexpected exceptions and even system-exiting exceptions. This can hide bugs and make failures difficult to diagnose.
5. What does raise do? It raises an exception explicitly. Developers use it to enforce validation and business rules.
6. Why create custom exceptions? Custom exceptions represent application-specific failures. They let callers handle business conditions separately.
7. What is exception chaining? It preserves the original exception when raising a higher-level exception. Python supports it through raise NewError() from error.
8. What is the difference between logging.error and logging.exception? Both log error-level messages. logging.exception() also includes exception traceback information when called inside an exception handler.
9. Does finally always execute? It normally executes during Python's exception-handling flow. It is not an absolute guarantee during process termination, interpreter crashes or forced shutdown.
10. Why is the with statement preferred for files? It manages the file's lifecycle and closes it automatically when the block exits, including when an exception occurs.

12. Hands-On Practice

Exercise 1 – Safe division Write a function that accepts two numbers. Handle invalid input and division by zero separately.
Exercise 2 – File reader Read a text file using with. Handle a missing file and print a useful message.
Exercise 3 – Bank withdrawal Create a custom InsufficientBalanceError. Raise it when a withdrawal exceeds the account balance.
Exercise 4 – API failure handling Write a function that calls an external API. Handle connection failures and timeouts separately. Do not expose credentials in logs.

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.

Key takeaway

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.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.