Understanding when to raise which error is a senior-level programming skill — especially important for clean architecture, APIs, ETL pipelines, and LLM systems like the ones you are building.
I’ll explain this in a very intuitive, real-life, and practical way, with:
🧠 mental models
🚦 when to raise which error
🧪 real code examples
📦 common errors you actually encounter in day-to-day programming
Raising an error is like stopping the program at the exact point where something becomes invalid.
Think of it as:
❌ “I refuse to continue because something is fundamentally wrong.”
Errors are not failures — they are guards 🛡️.
| Situation | Equivalent Error |
|---|---|
| Wrong PIN in ATM | ValueError |
| Electricity not available | EnvironmentError |
| Door locked | PermissionError |
| Asking for 6th floor in 5-floor building | IndexError |
| Calling a person who doesn’t exist | AttributeError |
ValueError – ❌ Wrong Value (Most Common)ValueErrorRaise ValueError when:
Type is correct ✅
But value is logically invalid ❌
“I understand your input, but its value doesn’t make sense.”
def set_age(age):
if age <= 0:
raise ValueError("Age must be positive")
✔ age is an int
❌ but -5 is invalid
if chunk_size <= 0:
raise ValueError("chunk_size must be greater than 0")
Invalid thresholds
Empty strings where not allowed
Invalid enum values
Out-of-range numbers
TypeError – ❌ Wrong TypeTypeErrorRaise when:
Type itself is wrong
Operation cannot proceed
“I don’t even understand what you gave me.”
def calculate_discount(price):
if not isinstance(price, (int, float)):
raise TypeError("Price must be a number")
String instead of number
List instead of dict
None where object expected
EnvironmentError / OSError – 🌍 System / Environment Problem⚠️ In modern Python,
EnvironmentErroris an alias ofOSError
Raise when:
Problem is outside your code
OS, environment variables, file system, network
“Your system environment is not ready.”
if os.getenv("GOOGLE_API_KEY") is None:
raise EnvironmentError("GOOGLE_API_KEY not set")
File not found
Disk full
Permission denied
Network unavailable
FileNotFoundError – 📄 File MissingSubclass of OSError
if not os.path.exists(file_path):
raise FileNotFoundError(f"{file_path} not found")
File is mandatory
Cannot continue without it
PermissionError – 🔒 No Access“The file exists, but you’re not allowed.”
if not os.access(path, os.R_OK):
raise PermissionError("Read permission denied")
KeyError – 🔑 Missing Dictionary Keyif "llm" not in config:
raise KeyError("Missing 'llm' section in config")
JSON configs
API responses
YAML files
IndexError – 📦 Out of Rangeif index >= len(items):
raise IndexError("Index out of range")
Lists
Tuples
Pagination logic
AttributeError – 🧩 Missing Attribute“This object doesn’t have what you’re asking for.”
if not hasattr(obj, "embed_query"):
raise AttributeError("Embedding model missing embed_query()")
🔥 You’ve already faced this in LangChain imports 😉
RuntimeError – ⚙️ Program State is WrongLogic error
State inconsistency
Should never happen normally
if self.vectorstore is None:
raise RuntimeError("Vector store not initialized")
NotImplementedError – 🚧 Feature Placeholderdef load_llm(self):
raise NotImplementedError("LLM provider not implemented yet")
Used in:
Abstract classes
Base interfaces
TimeoutError – ⏳ Operation Took Too Longraise TimeoutError("Request to API timed out")
Used in:
APIs
Web scraping
LLM calls
Custom Exceptions – 🧑🎨 Best PracticeFor production systems, create your own errors.
class ConfigurationError(Exception):
pass
if "embedding" not in config:
raise ConfigurationError("Embedding config missing")
✔ Cleaner logs
✔ Better debugging
✔ Better error handling
| Situation | Raise |
|---|---|
| Wrong value | ValueError |
| Wrong type | TypeError |
| Missing env variable | EnvironmentError |
| File missing | FileNotFoundError |
| No permission | PermissionError |
| Missing dict key | KeyError |
| Index out of range | IndexError |
| Missing object method | AttributeError |
| Bad app state | RuntimeError |
| Feature not built | NotImplementedError |
For your:
🔗 LangChain pipelines
🛒 Scrapers
🧠 LLM loaders
⚙️ ETL systems
👉 Always:
Validate early
Raise specific errors
Never silently fail
Log before raising (production)