• About TC
  • Affiliate Disclaimer
  • Privacy Policy
  • TOS
  • Contact
Wednesday, June 18, 2025
Techcratic
  • TC
  • AI
    Artificial Intelligence

    How Apollo Tyres is unlocking machine insights using agentic AI-powered Manufacturing Reasoner

    Artificial Intelligence

    Automatically Build AI Workflows with Magical AI

    Artificial Intelligence

    Amazon Nova Lite enables Bito to offer a free tier option for its AI-powered code reviews

    Artificial Intelligence

    Bridging the Gap: New Datasets Push Recommender Research Toward Real-World Scale

    Artificial Intelligence

    7 Python Errors That Are Actually Features

    Artificial Intelligence

    10 Awesome OCR Models for 2025

    Artificial Intelligence

    5 Error Handling Patterns in Python (Beyond Try-Except)

    Artificial Intelligence

    Top 5 Alternative Data Career Paths and How to Learn Them for Free

    Artificial Intelligence

    Implementing Machine Learning Pipelines with Apache Spark

  • Crypto
    Bitmex Co-Founder Arthur Hayes Has a Stark Prediction for ‘Circle Copycat’ Stocks

    Bitmex Co-Founder Arthur Hayes Has a Stark Prediction for ‘Circle Copycat’ Stocks

    Bitcoin Bull Cycle is Over: CryptoQuant CEO

    US Senate Passes First Major Stablecoin Regulation Bill

    Ripple and SEC Ask Court to Pause Appeals as They Fight to End XRP Case

    Ripple and SEC Ask Court to Pause Appeals as They Fight to End XRP Case

    Bitcoin Trades Near $102K Support as FOMC Triggers Selling

    Bitcoin Trades Near $102K Support as FOMC Triggers Selling

    Uniswap Surges 24% on $88B Volume, Targeting $12

    Pump.fun Accused of Stealing $741 M in Fees, Critics Warn

    Canada Approves First XRP Spot ETF on Toronto Stock Exchange

    Canada Approves First XRP Spot ETF on Toronto Stock Exchange

    Fold Announces $250M Equity Deal to Bolster Bitcoin Treasury

    Fold Announces $250M Equity Deal to Bolster Bitcoin Treasury

    Key BTC price levels to watch as fed rate cut hopes fade

    Key BTC price levels to watch as fed rate cut hopes fade

    Theminermag Bitcoin Mining Update: May/June 2025

    Theminermag Bitcoin Mining Update: May/June 2025

  • Cybersecurity
    Cybersecurity

    Ex-CIA Analyst Sentenced to 37 Months for Leaking Top Secret National Defense Documents

    Cybersecurity

    Critical RCE Bug Rated 9.9 CVSS in Backup & Replication

    Cybersecurity

    Hard-Coded ‘b’ Password in Sitecore XP Sparks Major RCE Risk in Enterprise Deployments

    Cybersecurity

    AI Agents Run on Secret Accounts — Learn How to Secure Them in This Webinar

    Cybersecurity

    How to Address the Expanding Security Risk

    Cybersecurity

    ConnectWise to Rotate ScreenConnect Code Signing Certificates Due to Security Risks

    Cybersecurity

    5 Lessons from River Island

    Cybersecurity

    INTERPOL Dismantles 20,000+ Malicious IPs Linked to 69 Malware Variants in Operation Secure

    Cybersecurity

    SinoTrack GPS Devices Vulnerable to Remote Vehicle Control via Default Passwords

  • Deals
    ASRock Motherboard B760M-HDV/M.2 Intel 12th and 13th Generation CPU (LGA1700) Compatible…

    ASRock Motherboard B760M-HDV/M.2 Intel 12th and 13th Generation CPU (LGA1700) Compatible…

    2018 Apple iPad Pro (12.9-inch, Wi-Fi, 256GB) – Silver (Renewed)

    2018 Apple iPad Pro (12.9-inch, Wi-Fi, 256GB) – Silver (Renewed)

    MageGee SKY98 Mechanical Gaming Keyboard, 96% Gasket Hot Swappable Wired Custom Creamy…

    MageGee SKY98 Mechanical Gaming Keyboard, 96% Gasket Hot Swappable Wired Custom Creamy…

    Sceptre 27-inch FHD 1080p IPS Gaming LED Monitor up to 165Hz 144Hz 1ms DisplayPort HDMI,…

    Sceptre 27-inch FHD 1080p IPS Gaming LED Monitor up to 165Hz 144Hz 1ms DisplayPort HDMI,…

    Razer Enki X Essential Gaming Chair: All-Day Comfort – Built-in Lumbar Arch – Optimized…

    Razer Enki X Essential Gaming Chair: All-Day Comfort – Built-in Lumbar Arch – Optimized…

    MSI Thin 15.6 inch FHD 144Hz Gaming Laptop Intel Core i5-13420H NVIDIA GeForce RTX…

    MSI Thin 15.6 inch FHD 144Hz Gaming Laptop Intel Core i5-13420H NVIDIA GeForce RTX…

    Sonic’s Ultimate Genesis Collection (Platinum Hits) – Xbox 360 (Renewed)

    Sonic’s Ultimate Genesis Collection (Platinum Hits) – Xbox 360 (Renewed)

    Donkey Kong Country Returns (Renewed)

    Donkey Kong Country Returns (Renewed)

    Buffalo Games CHRONOLOGY – The Game Where You Make History – 20th Anniversary Edition

    Buffalo Games CHRONOLOGY – The Game Where You Make History – 20th Anniversary Edition

  • Gaming
    HOW TO REACH RYKARD LORD OF BLASPHEMY BOSS LOCATION / HOW TO REACH VOLCANO MANOR – ELDEN RING

    HOW TO REACH RYKARD LORD OF BLASPHEMY BOSS LOCATION / HOW TO REACH VOLCANO MANOR – ELDEN RING

    Maliketh Black Blade Build 2025 VS Main Bosses + DLC – Elden Ring Colossal Sword Build Patch 1.16

    Maliketh Black Blade Build 2025 VS Main Bosses + DLC – Elden Ring Colossal Sword Build Patch 1.16

    OGL BACKLASH As Dungeon And Dragons Movie Faces Boycott

    OGL BACKLASH As Dungeon And Dragons Movie Faces Boycott

    Overwatch 2 Season 17 is finally giving power back to the people by introducing map voting for quick play and competitive

    Overwatch 2 Season 17 is finally giving power back to the people by introducing map voting for quick play and competitive

    The Legend of Zelda: Breath of the Wild – Monya Toma Shrine Walkthrough [HD 1080P]

    The Legend of Zelda: Breath of the Wild – Monya Toma Shrine Walkthrough [HD 1080P]

    BOTW – Lynel Hunting II – Walkthrough 27, pt. 5

    BOTW – Lynel Hunting II – Walkthrough 27, pt. 5

    Top 4 SECRET Broken Black Myth: Wukong Builds (Most OP Builds That You Missed Out On)

    Top 4 SECRET Broken Black Myth: Wukong Builds (Most OP Builds That You Missed Out On)

    Is Baldur’s Gate 3 Worth the Hype?

    Is Baldur’s Gate 3 Worth the Hype?

    Could The Mario Movie Be What The Next Mario Game Is Like?! Open World Mario!?

    Could The Mario Movie Be What The Next Mario Game Is Like?! Open World Mario!?

  • Tesla
    Custom Fit Tesla Cybertruck 2024 2025 Sunshade Umbrella -100% Blackout Ratio Thickened…

    Custom Fit Tesla Cybertruck 2024 2025 Sunshade Umbrella -100% Blackout Ratio Thickened…

    KEEPER Portable Trunk Organizer, 19L, Car Organizers and Storage, Non-Slip Bottom,…

    KEEPER Portable Trunk Organizer, 19L, Car Organizers and Storage, Non-Slip Bottom,…

    ARKSEN 64 x 39 x 4 Inch Upgrade Universal Roof Rack – 250Lbs Capacity Heavy Duty Rooftop…

    ARKSEN 64 x 39 x 4 Inch Upgrade Universal Roof Rack – 250Lbs Capacity Heavy Duty Rooftop…

    2025 Upgrade Sunshade Roof for Tesla Model Y Accessories, [Graphene Cooling Tech & High…

    2025 Upgrade Sunshade Roof for Tesla Model Y Accessories, [Graphene Cooling Tech & High…

    Tesla (TSLA) is sitting on so much inventory it has to take over parking lots all over the US

    Tesla (TSLA) is sitting on so much inventory it has to take over parking lots all over the US

    Tesla (TSLA) plans to pause production at Gigafactory Texas for second time in 2 months

    DEWALT CCS1 to NACS Fast Charging Adapter for All 2021 and Newer Tesla Models Excluding…

    DEWALT CCS1 to NACS Fast Charging Adapter for All 2021 and Newer Tesla Models Excluding…

    6PCS Trunk Mats & Frunk Mat & Backrest Mats for New 2025 2026 Tesla Model Y Juniper…

    6PCS Trunk Mats & Frunk Mat & Backrest Mats for New 2025 2026 Tesla Model Y Juniper…

    Tesla gives update on Tesla Semi factory, says on track for volume production in 2026

    Tesla gears up to start selling Tesla Semi electric truck in Europe

  • UFO
    Jellyfish UFO Shoots Green Laser Beam: New Evidence #shorts #lab360

    Jellyfish UFO Shoots Green Laser Beam: New Evidence #shorts #lab360

    Mind-Blowing Celebrity Encounters: Uncovering Unknown Stories and Unexpected Reactions

    Mind-Blowing Celebrity Encounters: Uncovering Unknown Stories and Unexpected Reactions

    Alien Abductions: Real Accounts and Theories #AlienAbductions #Extraterrestrial #Mystery #short

    Alien Abductions: Real Accounts and Theories #AlienAbductions #Extraterrestrial #Mystery #short

    ’UFO’ spotted by Beijing residents #shorts

    ’UFO’ spotted by Beijing residents #shorts

    Roswell Revisited

    Roswell Revisited

    The Bizarre Colares UFO Attack | Shocking Truth Behind Brazil's Biggest UFO Encounter

    The Bizarre Colares UFO Attack | Shocking Truth Behind Brazil's Biggest UFO Encounter

    The Alien Experiment | He saw Aliens #vigyanrecharge

    The Alien Experiment | He saw Aliens #vigyanrecharge

    UFO Completes 5 Orbits Around the Moon?! | Ancient Aliens | #Shorts

    UFO Completes 5 Orbits Around the Moon?! | Ancient Aliens | #Shorts

    A Pleiadian Contactee Describes His Experience

    A Pleiadian Contactee Describes His Experience

No Result
View All Result
  • TC
  • AI
    Artificial Intelligence

    How Apollo Tyres is unlocking machine insights using agentic AI-powered Manufacturing Reasoner

    Artificial Intelligence

    Automatically Build AI Workflows with Magical AI

    Artificial Intelligence

    Amazon Nova Lite enables Bito to offer a free tier option for its AI-powered code reviews

    Artificial Intelligence

    Bridging the Gap: New Datasets Push Recommender Research Toward Real-World Scale

    Artificial Intelligence

    7 Python Errors That Are Actually Features

    Artificial Intelligence

    10 Awesome OCR Models for 2025

    Artificial Intelligence

    5 Error Handling Patterns in Python (Beyond Try-Except)

    Artificial Intelligence

    Top 5 Alternative Data Career Paths and How to Learn Them for Free

    Artificial Intelligence

    Implementing Machine Learning Pipelines with Apache Spark

  • Crypto
    Bitmex Co-Founder Arthur Hayes Has a Stark Prediction for ‘Circle Copycat’ Stocks

    Bitmex Co-Founder Arthur Hayes Has a Stark Prediction for ‘Circle Copycat’ Stocks

    Bitcoin Bull Cycle is Over: CryptoQuant CEO

    US Senate Passes First Major Stablecoin Regulation Bill

    Ripple and SEC Ask Court to Pause Appeals as They Fight to End XRP Case

    Ripple and SEC Ask Court to Pause Appeals as They Fight to End XRP Case

    Bitcoin Trades Near $102K Support as FOMC Triggers Selling

    Bitcoin Trades Near $102K Support as FOMC Triggers Selling

    Uniswap Surges 24% on $88B Volume, Targeting $12

    Pump.fun Accused of Stealing $741 M in Fees, Critics Warn

    Canada Approves First XRP Spot ETF on Toronto Stock Exchange

    Canada Approves First XRP Spot ETF on Toronto Stock Exchange

    Fold Announces $250M Equity Deal to Bolster Bitcoin Treasury

    Fold Announces $250M Equity Deal to Bolster Bitcoin Treasury

    Key BTC price levels to watch as fed rate cut hopes fade

    Key BTC price levels to watch as fed rate cut hopes fade

    Theminermag Bitcoin Mining Update: May/June 2025

    Theminermag Bitcoin Mining Update: May/June 2025

  • Cybersecurity
    Cybersecurity

    Ex-CIA Analyst Sentenced to 37 Months for Leaking Top Secret National Defense Documents

    Cybersecurity

    Critical RCE Bug Rated 9.9 CVSS in Backup & Replication

    Cybersecurity

    Hard-Coded ‘b’ Password in Sitecore XP Sparks Major RCE Risk in Enterprise Deployments

    Cybersecurity

    AI Agents Run on Secret Accounts — Learn How to Secure Them in This Webinar

    Cybersecurity

    How to Address the Expanding Security Risk

    Cybersecurity

    ConnectWise to Rotate ScreenConnect Code Signing Certificates Due to Security Risks

    Cybersecurity

    5 Lessons from River Island

    Cybersecurity

    INTERPOL Dismantles 20,000+ Malicious IPs Linked to 69 Malware Variants in Operation Secure

    Cybersecurity

    SinoTrack GPS Devices Vulnerable to Remote Vehicle Control via Default Passwords

  • Deals
    ASRock Motherboard B760M-HDV/M.2 Intel 12th and 13th Generation CPU (LGA1700) Compatible…

    ASRock Motherboard B760M-HDV/M.2 Intel 12th and 13th Generation CPU (LGA1700) Compatible…

    2018 Apple iPad Pro (12.9-inch, Wi-Fi, 256GB) – Silver (Renewed)

    2018 Apple iPad Pro (12.9-inch, Wi-Fi, 256GB) – Silver (Renewed)

    MageGee SKY98 Mechanical Gaming Keyboard, 96% Gasket Hot Swappable Wired Custom Creamy…

    MageGee SKY98 Mechanical Gaming Keyboard, 96% Gasket Hot Swappable Wired Custom Creamy…

    Sceptre 27-inch FHD 1080p IPS Gaming LED Monitor up to 165Hz 144Hz 1ms DisplayPort HDMI,…

    Sceptre 27-inch FHD 1080p IPS Gaming LED Monitor up to 165Hz 144Hz 1ms DisplayPort HDMI,…

    Razer Enki X Essential Gaming Chair: All-Day Comfort – Built-in Lumbar Arch – Optimized…

    Razer Enki X Essential Gaming Chair: All-Day Comfort – Built-in Lumbar Arch – Optimized…

    MSI Thin 15.6 inch FHD 144Hz Gaming Laptop Intel Core i5-13420H NVIDIA GeForce RTX…

    MSI Thin 15.6 inch FHD 144Hz Gaming Laptop Intel Core i5-13420H NVIDIA GeForce RTX…

    Sonic’s Ultimate Genesis Collection (Platinum Hits) – Xbox 360 (Renewed)

    Sonic’s Ultimate Genesis Collection (Platinum Hits) – Xbox 360 (Renewed)

    Donkey Kong Country Returns (Renewed)

    Donkey Kong Country Returns (Renewed)

    Buffalo Games CHRONOLOGY – The Game Where You Make History – 20th Anniversary Edition

    Buffalo Games CHRONOLOGY – The Game Where You Make History – 20th Anniversary Edition

  • Gaming
    HOW TO REACH RYKARD LORD OF BLASPHEMY BOSS LOCATION / HOW TO REACH VOLCANO MANOR – ELDEN RING

    HOW TO REACH RYKARD LORD OF BLASPHEMY BOSS LOCATION / HOW TO REACH VOLCANO MANOR – ELDEN RING

    Maliketh Black Blade Build 2025 VS Main Bosses + DLC – Elden Ring Colossal Sword Build Patch 1.16

    Maliketh Black Blade Build 2025 VS Main Bosses + DLC – Elden Ring Colossal Sword Build Patch 1.16

    OGL BACKLASH As Dungeon And Dragons Movie Faces Boycott

    OGL BACKLASH As Dungeon And Dragons Movie Faces Boycott

    Overwatch 2 Season 17 is finally giving power back to the people by introducing map voting for quick play and competitive

    Overwatch 2 Season 17 is finally giving power back to the people by introducing map voting for quick play and competitive

    The Legend of Zelda: Breath of the Wild – Monya Toma Shrine Walkthrough [HD 1080P]

    The Legend of Zelda: Breath of the Wild – Monya Toma Shrine Walkthrough [HD 1080P]

    BOTW – Lynel Hunting II – Walkthrough 27, pt. 5

    BOTW – Lynel Hunting II – Walkthrough 27, pt. 5

    Top 4 SECRET Broken Black Myth: Wukong Builds (Most OP Builds That You Missed Out On)

    Top 4 SECRET Broken Black Myth: Wukong Builds (Most OP Builds That You Missed Out On)

    Is Baldur’s Gate 3 Worth the Hype?

    Is Baldur’s Gate 3 Worth the Hype?

    Could The Mario Movie Be What The Next Mario Game Is Like?! Open World Mario!?

    Could The Mario Movie Be What The Next Mario Game Is Like?! Open World Mario!?

  • Tesla
    Custom Fit Tesla Cybertruck 2024 2025 Sunshade Umbrella -100% Blackout Ratio Thickened…

    Custom Fit Tesla Cybertruck 2024 2025 Sunshade Umbrella -100% Blackout Ratio Thickened…

    KEEPER Portable Trunk Organizer, 19L, Car Organizers and Storage, Non-Slip Bottom,…

    KEEPER Portable Trunk Organizer, 19L, Car Organizers and Storage, Non-Slip Bottom,…

    ARKSEN 64 x 39 x 4 Inch Upgrade Universal Roof Rack – 250Lbs Capacity Heavy Duty Rooftop…

    ARKSEN 64 x 39 x 4 Inch Upgrade Universal Roof Rack – 250Lbs Capacity Heavy Duty Rooftop…

    2025 Upgrade Sunshade Roof for Tesla Model Y Accessories, [Graphene Cooling Tech & High…

    2025 Upgrade Sunshade Roof for Tesla Model Y Accessories, [Graphene Cooling Tech & High…

    Tesla (TSLA) is sitting on so much inventory it has to take over parking lots all over the US

    Tesla (TSLA) is sitting on so much inventory it has to take over parking lots all over the US

    Tesla (TSLA) plans to pause production at Gigafactory Texas for second time in 2 months

    DEWALT CCS1 to NACS Fast Charging Adapter for All 2021 and Newer Tesla Models Excluding…

    DEWALT CCS1 to NACS Fast Charging Adapter for All 2021 and Newer Tesla Models Excluding…

    6PCS Trunk Mats & Frunk Mat & Backrest Mats for New 2025 2026 Tesla Model Y Juniper…

    6PCS Trunk Mats & Frunk Mat & Backrest Mats for New 2025 2026 Tesla Model Y Juniper…

    Tesla gives update on Tesla Semi factory, says on track for volume production in 2026

    Tesla gears up to start selling Tesla Semi electric truck in Europe

  • UFO
    Jellyfish UFO Shoots Green Laser Beam: New Evidence #shorts #lab360

    Jellyfish UFO Shoots Green Laser Beam: New Evidence #shorts #lab360

    Mind-Blowing Celebrity Encounters: Uncovering Unknown Stories and Unexpected Reactions

    Mind-Blowing Celebrity Encounters: Uncovering Unknown Stories and Unexpected Reactions

    Alien Abductions: Real Accounts and Theories #AlienAbductions #Extraterrestrial #Mystery #short

    Alien Abductions: Real Accounts and Theories #AlienAbductions #Extraterrestrial #Mystery #short

    ’UFO’ spotted by Beijing residents #shorts

    ’UFO’ spotted by Beijing residents #shorts

    Roswell Revisited

    Roswell Revisited

    The Bizarre Colares UFO Attack | Shocking Truth Behind Brazil's Biggest UFO Encounter

    The Bizarre Colares UFO Attack | Shocking Truth Behind Brazil's Biggest UFO Encounter

    The Alien Experiment | He saw Aliens #vigyanrecharge

    The Alien Experiment | He saw Aliens #vigyanrecharge

    UFO Completes 5 Orbits Around the Moon?! | Ancient Aliens | #Shorts

    UFO Completes 5 Orbits Around the Moon?! | Ancient Aliens | #Shorts

    A Pleiadian Contactee Describes His Experience

    A Pleiadian Contactee Describes His Experience

No Result
View All Result
Techcratic
No Result
View All Result
Home AI

5 Error Handling Patterns in Python (Beyond Try-Except)

AI by AI
June 6, 2025
in AI
Reading Time: 9 mins read
121 9
A A
0

Kanwal Mehreen
2025-06-06 10:00:00
www.kdnuggets.com

5 Error Handling Patterns in PythonImage by Author | Canva

 

When it comes to error handling, the first thing we usually learn is how to use try-except blocks. But is that really enough as our codebase grows more complex? I believe not. Relying solely on try-except can lead to repetitive, cluttered, and hard-to-maintain code.

In this article, I’ll walk you through 5 advanced yet practical error handling patterns that can make your code cleaner, more reliable, and easier to debug. Each pattern comes with a real-world example so you can clearly see where and why it makes sense. So, let’s get started.

 

1. Error Aggregation for Batch Processing

 
When processing multiple items (e.g., in a loop), you might want to continue processing even if some items fail, then report all errors at the end. This pattern, called error aggregation, avoids stopping on the first failure. This pattern is excellent for form validation, data import scenarios, or any situation where you want to provide comprehensive feedback about all issues rather than stopping at the first error.

Example: Processing a list of user records. Continue even if some fail.

def process_user_record(record, record_number):
    if not record.get("email"):
        raise ValueError(f"Record #{record_number} failed: Missing email in record {record}")
    
    # Simulate processing
    print(f"Processed user #{record_number}: {record['email']}")

def process_users(records):
    errors = []
    for index, record in enumerate(records, start=1):  
        try:
            process_user_record(record, index)
        except ValueError as e:
            errors.append(str(e))
    return errors

users = [
    {"email": "qasim@example.com"},
    {"email": ""},
    {"email": "zeenat@example.com"},
    {"email": ""}
]

errors = process_users(users)

if errors:
    print("\nProcessing completed with errors:")
    for error in errors:
        print(f"- {error}")
else:
    print("All records processed successfully")

 
This code loops through user records and processes each one individually. If a record is missing an email, it raises a ValueError, which is caught and stored in the errors list. The process continues for all records, and any failures are reported at the end without stopping the entire batch like this:

Output:
Processed user #1: qasim@example.com
Processed user #3: zeenat@example.com

Processing completed with errors:
- Record #2 failed: Missing email in record {'email': ''}
- Record #4 failed: Missing email in record {'email': ''}

 

2. Context Manager Pattern for Resource Management

 
When working with resources like files, database connections, or network sockets, you need to ensure they’re properly opened and closed, even if an error occurs. Context managers, using the with statement, handle this automatically, reducing the chance of resource leaks compared to manual try-finally blocks. This pattern is especially helpful for I/O operations or when dealing with external systems.

Example: Let’s say you’re reading a CSV file and want to ensure it’s closed properly, even if processing the file fails.

import csv

def read_csv_data(file_path):
    try:
        with open(file_path, 'r') as file:
            print(f"Inside 'with': file.closed = {file.closed}")  # Should be False
            reader = csv.reader(file)
            for row in reader:
                if len(row) 

 
This code uses a with statement (context manager) to safely open and read the file. If any row has fewer than 2 values, it raises a ValueError, but the file still gets closed automatically. The file.closed checks confirm the file’s state both inside and after the with block—even in case of an error. Let’s run the above code to observe this behavior:

Output:
Inside 'with': file.closed = False
['Name', 'Age']
['Sarwar', '30']
Error: Invalid row format
In except block: file is closed? True

 

3. Exception Wrapping for Contextual Errors

 
Sometimes, an exception in a lower-level function doesn’t provide enough context about what went wrong in the broader application. Exception wrapping (or chaining) lets you catch an exception, add context, and re-raise a new exception that includes the original one. It’s especially useful in layered applications (e.g., APIs or services).

Example: Suppose you’re fetching user data from a database and want to provide context when a database error occurs.

class DatabaseAccessError(Exception):
    """Raised when database operations fail."""
    pass

def fetch_user(user_id):
    try:
        # Simulate database query
        raise ConnectionError("Failed to connect to database")
    except ConnectionError as e:
        raise DatabaseAccessError(f"Failed to fetch user {user_id}") from e

try:
    fetch_user(123)
except DatabaseAccessError as e:
    print(f"Error: {e}")
    print(f"Caused by: {e.__cause__}")

 

The ConnectionError is caught and wrapped in a DatabaseAccessError with additional context about the user ID. The from e syntax links the original exception, so the full error chain is available for debugging. The output might look like this:

Output:
Error: Failed to fetch user 123
Caused by: Failed to connect to database

 

4. Retry Logic for Transient Failures

 
Some errors, like network timeouts or temporary service unavailability, are transient and may resolve on retry. Using a retry pattern can handle these gracefully without cluttering your code with manual loops. It automates recovery from temporary failures.

Example: Let’s retry a flaky API call that occasionally fails due to simulated network errors. The code below attempts the API call multiple times with a fixed delay between retries. If the call succeeds, it returns the result immediately. If all retries fail, it raises an exception to be handled by the caller.

import random
import time

def flaky_api_call():
    # Simulate 50% chance of failure (like timeout or server error)
    if random.random() 

 

Output:
Attempt 1 failed: Simulated network failure. Retrying in 2 seconds...
API call succeeded: {'status': 'success', 'data': [1, 2, 3]}

 
As you can see, the first attempt failed due to the simulated network error (which happens randomly 50% of the time). The retry logic waited for 2 seconds and then successfully completed the API call on the next attempt.

 

5. Custom Exception Classes for Domain-Specific Errors

 
Instead of relying on generic exceptions like ValueError or RuntimeError, you can create custom exception classes to represent specific errors in your application’s domain. This makes error handling more semantic and easier to maintain.

Example: Suppose a payment processing system where different types of payment failures need specific handling.

class PaymentError(Exception):
    """Base class for payment-related exceptions."""
    pass

class InsufficientFundsError(PaymentError):
    """Raised when the account has insufficient funds."""
    pass

class InvalidCardError(PaymentError):
    """Raised when the card details are invalid."""
    pass

def process_payment(amount, card_details):
    try:
        if amount > 1000:
            raise InsufficientFundsError("Not enough funds for this transaction")
        if not card_details.get("valid"):
            raise InvalidCardError("Invalid card details provided")
        print("Payment processed successfully")
    except InsufficientFundsError as e:
        print(f"Payment failed: {e}")
        # Notify user to top up account
    except InvalidCardError as e:
        print(f"Payment failed: {e}")
        # Prompt user to re-enter card details
    except Exception as e:
        print(f"Unexpected error: {e}")
        # Log for debugging

process_payment(1500, {"valid": False})

 

Custom exceptions (InsufficientFundsError, InvalidCardError) inherit from a base PaymentError class, allowing you to handle specific payment issues differently while catching unexpected errors with a generic Exception block. For example, In the call process_payment(1500, {“valid”: False}), the first check triggers because the amount (1500) exceeds 1000, so it raises InsufficientFundsError. This exception is caught in the corresponding except block, printing:

Output:
Payment failed: Not enough funds for this transaction

 

Conclusion

 
That’s it. In this article, we explored 5 practical error handling patterns:

  1. Error Aggregation: Process all items, collect errors, and report them together
  2. Context Manager: Safely manage resources like files with with blocks
  3. Exception Wrapping: Add context by catching and re-raising exceptions
  4. Retry Logic: Automatically retry transient errors like network failures
  5. Custom Exceptions: Create specific error classes for clearer handling

Give these patterns a try in your next project. With a bit of practice, you’ll find your code easier to maintain and your error handling much more effective.
 
 

Kanwal Mehreen Kanwal is a machine learning engineer and a technical writer with a profound passion for data science and the intersection of AI with medicine. She co-authored the ebook “Maximizing Productivity with ChatGPT”. As a Google Generation Scholar 2022 for APAC, she champions diversity and academic excellence. She’s also recognized as a Teradata Diversity in Tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having founded FEMCodes to empower women in STEM fields.

Source Link



Shark AI Ultra Voice Control Robot Vacuum

Transform your cleaning routine with the Shark AI Ultra Voice Control Robot Vacuum! This high-tech marvel boasts over 32,487 ratings, an impressive 4.2 out of 5 stars, and has been purchased over 900 times in the past month. Perfect for keeping your home spotless with minimal effort, this vacuum is now available for the unbeatable price of $349.99!

Don’t miss out on this limited-time offer. Order now and let Shark AI do the work for you!


Start your free Amazon Prime trial
today and unlock unlimited streaming and more!

Help Power Techcratic’s Future – Scan To Support

If Techcratic’s content and insights have helped you, consider giving back by supporting the platform with crypto. Every contribution makes a difference, whether it’s for high-quality content, server maintenance, or future updates. Techcratic is constantly evolving, and your support helps drive that progress.

As a solo operator who wears all the hats, creating content, managing the tech, and running the site, your support allows me to stay focused on delivering valuable resources. Your support keeps everything running smoothly and enables me to continue creating the content you love. I’m deeply grateful for your support, it truly means the world to me! Thank you!

BITCOIN

Bitcoin Logo

Bitcoin QR Code

bc1qlszw7elx2qahjwvaryh0tkgg8y68enw30gpvge

Scan the QR code with your crypto wallet app

DOGECOIN

Dogecoin Logo

Dogecoin QR Code

D64GwvvYQxFXYyan3oQCrmWfidf6T3JpBA

Scan the QR code with your crypto wallet app

ETHEREUM

Ethereum Logo

Ethereum QR Code

0xe9BC980DF3d985730dA827996B43E4A62CCBAA7a

Scan the QR code with your crypto wallet app

Please read the Privacy and Security Disclaimer on how Techcratic handles your support.

Disclaimer: As an Amazon Associate, Techcratic may earn from qualifying purchases.

Tags: AI NEWS
Share161ShareTweet101
Previous Post

Leak reveals which Apple Watches will run watchOS 26

Next Post

‘Screenbox’ Is a Sleek and Capable VLC-Based Video Player for Windows

AI

AI

Explore the dynamic realm of AI, where breakthroughs and trends are shaping the future. Stay informed and see how AI is making an impact. Don’t miss the crucial updates—read the latest articles here at Techcratic.

Related Posts

Artificial Intelligence
AI

How Apollo Tyres is unlocking machine insights using agentic AI-powered Manufacturing Reasoner

June 16, 2025
1.3k
Artificial Intelligence
AI

Automatically Build AI Workflows with Magical AI

June 16, 2025
1.3k
Artificial Intelligence
AI

Amazon Nova Lite enables Bito to offer a free tier option for its AI-powered code reviews

June 11, 2025
1.4k
Artificial Intelligence
AI

Bridging the Gap: New Datasets Push Recommender Research Toward Real-World Scale

June 11, 2025
1.3k
Artificial Intelligence
AI

7 Python Errors That Are Actually Features

June 10, 2025
1.3k
Artificial Intelligence
AI

10 Awesome OCR Models for 2025

June 6, 2025
1.3k
Artificial Intelligence
AI

Top 5 Alternative Data Career Paths and How to Learn Them for Free

June 5, 2025
1.3k
Artificial Intelligence
AI

Implementing Machine Learning Pipelines with Apache Spark

June 3, 2025
1.4k
Load More
Next Post
‘Screenbox’ Is a Sleek and Capable VLC-Based Video Player for Windows

'Screenbox' Is a Sleek and Capable VLC-Based Video Player for Windows

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Your Tech Resources

  • 30 Second Tech ™
  • AI
  • App Zone ™
  • Apple
  • Ars Technica
  • CNET
  • ComputerWorld
  • Crypto News
  • Cybersecurity
  • Endgadget
  • Forbes
  • Fossbytes
  • Gaming
  • GeekWire
  • Gizmodo
  • Google News
  • Hacker News
  • Harvard Tech
  • I Like Cats ™
  • I Like Dogs ™
  • LifeHacker
  • MacRumors
  • Macworld
  • Mashable
  • Microsoft
  • MIT Tech
  • PC World
  • Photofocus
  • Physics
  • Random Tech
  • Retro Rewind ™
  • Robot Report
  • SiliconANGLE
  • SlashGear
  • Smartphone
  • StackSocial
  • Tech Art
  • Tech Careers
  • Tech Deals
  • Techcratic ™
  • TechCrunch
  • Techdirt
  • TechRepublic
  • Techs Got To Eat ™
  • TechSpot
  • Tesla
  • The Verge
  • TNW
  • Trusted Reviews
  • UFO
  • VentureBeat
  • Visual Capitalist
  • Wired
  • ZDNet

Tech News

  • 30 Second Tech ™
  • AI
  • Apple Insider
  • Ars Technica
  • CNET
  • ComputerWorld
  • Crypto News
  • Cybersecurity
  • Endgadget
  • ExtremeTech
  • Fossbytes
  • Gaming
  • GeekWire
  • Gizmodo

Tech News

  • Harvard Tech
  • MacRumors
  • Macworld
  • Mashable
  • Microsoft
  • MIT Tech
  • Physics
  • PC World
  • Random Tech
  • Retro Rewind ™
  • SiliconANGLE
  • SlashGear
  • Smartphone
  • StackSocial
  • Tech Careers

Tech News​

  • Tech Art
  • TechCrunch
  • Techdirt
  • TechRepublic
  • Techs Got To Eat ™
  • TechSpot
  • Tesla
  • The Verge
  • TNW
  • Trusted Reviews
  • UFO
  • VentureBeat
  • Visual Capitalist
  • Wired
  • ZDNet

Site Links

  • About Techcratic
  • Affiliate Disclaimer
  • Affiliate Link Policy
  • Contact Techcratic
  • Dealors Discount Store
  • Privacy and Security Disclaimer
  • Privacy Policy
  • RSS Feed
  • Site Map
  • Support Techcratic
  • Techcratic
  • Tech Deals
  • TOS
  • 𝕏
Click For A Secret Deal

Techcratic – Your All In One Tech Hub © 2020 – 2025
All Rights Reserved
∞

No Result
View All Result
  • 30 Second Tech ™
  • AI
  • App Zone ™
  • Apple
  • Ars Technica
  • CNET
  • Crypto News
  • Cybersecurity
  • Endgadget
  • Gaming
  • I Like Cats ™
  • I Like Dogs ™
  • MacRumors
  • Macworld
  • Tech Deals
  • Techcratic ™
  • Techs Got To Eat ™
  • Tesla
  • UFO
  • Wired