Introduction to Error Handling in Python – Essential for Data Science 2026

Data Science Tool Box Mar 18, 2026

Introduction to Error Handling in Python – Essential for Data Science 2026

Error handling is a critical skill for building robust data science pipelines. In 2026, writing code that gracefully handles unexpected situations (missing files, bad data, API failures, etc.) is no longer optional — it is a professional requirement.

TL;DR — Core Error Handling Concepts

  • Use try / except to catch and handle errors
  • Use finally for cleanup code that must always run
  • Use else when you want code to run only if no exception occurred
  • Be specific with exception types instead of using bare except:

1. Basic Error Handling Structure

import pandas as pd

def load_sales_data(file_path: str):
    try:
        df = pd.read_csv(file_path, parse_dates=["order_date"])
        print(f"Successfully loaded {len(df)} records")
        return df
        
    except FileNotFoundError:
        print(f"❌ Error: File not found at {file_path}")
        return None
        
    except pd.errors.EmptyDataError:
        print("❌ Error: The file is empty")
        return None
        
    except Exception as e:           # Catch-all for unexpected errors
        print(f"❌ Unexpected error: {e}")
        return None

2. Real-World Data Science Example

def safe_data_processing(file_path: str):
    try:
        df = pd.read_csv(file_path)
        
        # Critical data cleaning steps
        df = df.dropna(subset=["amount", "customer_id"])
        df["order_date"] = pd.to_datetime(df["order_date"], errors="coerce")
        
        # If date conversion created NaNs, handle them
        if df["order_date"].isna().any():
            print(f"Warning: {df['order_date'].isna().sum()} invalid dates found")
            df = df.dropna(subset=["order_date"])
        
        return df
        
    except FileNotFoundError:
        print(f"File not found: {file_path}")
        raise                       # Re-raise if critical
        
    except Exception as e:
        print(f"Failed to process {file_path}: {e}")
        # Log the error or send alert here in production
        return None

3. Best Practices for Error Handling in Data Science 2026

  • Be specific with exception types (e.g., FileNotFoundError, ValueError, pd.errors.ParserError)
  • Always include a helpful error message
  • Use try/except around risky operations (file I/O, API calls, data parsing)
  • Use finally for cleanup (closing files, database connections, etc.)
  • Log errors properly instead of just printing them in production code
  • Consider raising custom exceptions for business logic errors

How try and except Work

Errors in Python are raised as exceptions. A try block runs code that might fail, except blocks handle specific exception types, else runs when no error occurred, and finally always runs, which suits clean-up work.

Catch the narrowest exception you expect, such as ValueError or KeyError, so real bugs are not hidden. Raise your own exceptions with clear messages when inputs are invalid.

Worked Example: Parsing Messy Values

A parser converts strings to numbers, counts failures and reports them.

def parse_all(raw):
    values, errors = [], []
    for item in raw:
        try:
            number = float(item)
        except (ValueError, TypeError) as err:
            errors.append((item, type(err).__name__))
        else:
            values.append(number)
        finally:
            pass
    return values, errors

ok, bad = parse_all(["3.5", "abc", None, "7"])
print(ok)
print(bad)

def check_positive(x):
    if x <= 0:
        raise ValueError(f"expected a positive number, got {x}")
    return x

try:
    check_positive(-2)
except ValueError as err:
    print(err)

abc raises a ValueError and None raises a TypeError, and both are recorded instead of crashing the loop. The custom error message explains exactly what went wrong.

Practical Tips

In data pipelines, error handling often means deciding what to do with bad records. Common choices are to skip them and keep a list for review, to replace them with a missing value, or to stop the whole run. The right answer depends on how costly a wrong result would be.

Logging is a better partner for except blocks than print. The logging module records time, severity and the full traceback with logger.exception, which makes failures in scheduled jobs much easier to investigate.

Test your error handling too. Passing deliberately bad input in a quick test proves that the except branch works and that the error message is helpful.

Common Mistakes

  • Using a bare except that hides every error.
  • Wrapping too much code in a single try block.
  • Silently ignoring errors without logging them.
  • Raising exceptions without helpful messages.

Quick Summary

  • try runs risky code; except handles named errors.
  • else runs on success; finally always runs.
  • Catch narrow exception types.
  • Raise clear errors for invalid input.

Conclusion

Robust error handling is what separates fragile scripts from production-grade data science code. In 2026, always anticipate where things can go wrong — especially with file loading, data parsing, and external API calls. Use specific except blocks, provide clear messages, and never let your pipeline crash silently on unexpected data.

Next steps:

  • Add proper error handling around file loading and data parsing steps in your current data science scripts

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices