Errors and Exceptions in Python – Essential Guide for Data Science 2026

Data Science Tool Box Mar 18, 2026

Errors and Exceptions in Python – Essential Guide for Data Science 2026

Understanding errors and exceptions is fundamental for building robust data science pipelines. In 2026, professional data scientists write code that not only works when everything goes right, but also handles failures gracefully with clear messages and appropriate recovery strategies.

TL;DR — Most Common Exception Types in Data Science

  • TypeError – Wrong data type passed to a function
  • ValueError – Correct type but invalid value
  • KeyError – Missing dictionary key or DataFrame column
  • FileNotFoundError – File or path does not exist
  • pd.errors.ParserError – Problems reading CSV/Excel files

1. Basic Exception Handling Structure

import pandas as pd

def load_and_process_data(file_path: str):
    try:
        df = pd.read_csv(file_path, parse_dates=["order_date"])
        
        # Critical processing steps
        df = df.dropna(subset=["amount", "customer_id"])
        df["profit"] = df["amount"] * 0.25
        
        return df
    
    except FileNotFoundError:
        print(f"❌ Could not find file: {file_path}")
        return None
        
    except pd.errors.EmptyDataError:
        print("❌ The file is empty or has no data.")
        return None
        
    except KeyError as e:
        print(f"❌ Missing required column: {e}")
        return None
        
    except Exception as e:          # Catch-all for unexpected errors
        print(f"❌ Unexpected error while processing data: {e}")
        # In production, you would log this properly
        return None

2. Advanced Error Handling Pattern

def safe_train_model(df: pd.DataFrame, target_column: str):
    try:
        if target_column not in df.columns:
            raise ValueError(f"Target column '{target_column}' not found. "
                           f"Available columns: {list(df.columns)}")
        
        # Training logic here...
        print(f"Training model with target: {target_column}")
        return {"status": "success", "accuracy": 0.88}
        
    except ValueError as e:
        print(f"Validation error: {e}")
        raise                       # Re-raise after logging
        
    except Exception as e:
        print(f"Critical error during model training: {e}")
        # Here you might log to a file or monitoring system
        raise RuntimeError("Model training failed") from e

3. Best Practices for Error Handling in Data Science 2026

  • Be specific with exception types rather than using bare except:
  • Provide clear, actionable error messages that help the user fix the problem
  • Use try/except around risky operations: file I/O, data parsing, model training, API calls
  • Log errors properly in production environments
  • Use custom exceptions for business logic errors when appropriate
  • Document which exceptions a function can raise in its docstring

Errors versus Exceptions

Syntax errors stop Python before any code runs, because the file cannot be parsed. Exceptions happen while the program runs, when an operation cannot complete, for example dividing by zero, opening a missing file or looking up a missing dictionary key.

Exceptions form a class hierarchy. KeyError and IndexError both inherit from LookupError, and almost everything inherits from Exception, so the type you catch decides how broad your handler is.

In data work, KeyError, ValueError, TypeError and FileNotFoundError cover most problems. Recognising them quickly from a traceback is one of the most useful debugging skills.

Worked Example: Common Exceptions in One Place

Each small operation below triggers a typical exception, which is caught and reported by name.

import pandas as pd

def run(label, func):
    try:
        func()
    except Exception as err:
        print(f"{label:12} -> {type(err).__name__}: {err}")

df = pd.DataFrame({"amount": [10, 20]})
run("missing key", lambda: {"a": 1}["b"])
run("bad index", lambda: [1, 2, 3][5])
run("bad value", lambda: int("ten"))
run("bad type", lambda: "a" + 1)
run("no file", lambda: open("missing.csv"))
run("no column", lambda: df["price"])

print(issubclass(KeyError, LookupError), issubclass(IndexError, LookupError))

Each line prints the exception name and message, which is exactly what you look for at the bottom of a traceback. A missing DataFrame column raises KeyError, the same type as a missing dictionary key.

Common Mistakes

  • Catching Exception in production code where a specific type is known.
  • Reading only the top of a traceback instead of the last line.
  • Confusing syntax errors with run-time exceptions.
  • Ignoring the exception message, which usually names the problem.

Quick Summary

  • Syntax errors stop parsing; exceptions happen at run time.
  • Exceptions form a hierarchy of classes.
  • KeyError, ValueError, TypeError and FileNotFoundError are the most common.
  • Read the last line of the traceback first.

Conclusion

Errors and exceptions are inevitable in data science work. In 2026, writing robust code means anticipating failures and handling them gracefully with specific exception types and helpful messages. Good error handling turns potential crashes into manageable situations and makes your data pipelines much more reliable and professional.

Next steps:

  • Add proper error handling around file loading, data parsing, and model training steps in your current projects

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