惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LINUX DO - 最新话题
G
Google Developers Blog
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
F
Full Disclosure
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
Help Net Security
Help Net Security
The Hacker News
The Hacker News
IT之家
IT之家
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
V
Visual Studio Blog
博客园 - 聂微东
Hacker News: Ask HN
Hacker News: Ask HN
H
Hacker News: Front Page
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Last Week in AI
Last Week in AI
Schneier on Security
Schneier on Security
N
News and Events Feed by Topic
博客园 - 【当耐特】
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
Google DeepMind News
Google DeepMind News
Cloudbric
Cloudbric
N
News | PayPal Newsroom
A
About on SuperTechFans
S
Schneier on Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hugging Face - Blog
Hugging Face - Blog
M
MIT News - Artificial intelligence
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
雷峰网
雷峰网
T
The Exploit Database - CXSecurity.com
罗磊的独立博客
K
Kaspersky official blog
The Cloudflare Blog
I
Intezer

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Error Handling Approaches: Exceptions or Result Types?
Mustafa ERBAY · 2026-05-30 · via DEV Community

Error handling has always been a topic I've focused on, and sometimes even debated, during software development. Especially in large and complex systems, how we handle errors directly impacts code readability, maintainability, and reliability. Over the years, I've extensively used both main approaches: Exceptions and Result types.

Both approaches have their own advantages and disadvantages. I've even personally witnessed how this choice led to critical decisions in a production ERP due to the complexity of its workflows. My goal here isn't to give you the "most correct" solution, but to explain why and when I chose one over the other based on my own experiences.

Exceptions: Why I Still Use Them

Exceptions are a traditional and common way of handling errors in many languages (like Java, C#, Python). The basic idea is that when an unexpected or abnormal situation occurs during an operation, the normal control flow is interrupted, and the error is thrown to the calling function or a higher layer. For me, Exceptions are still a valid option in many scenarios.

Exceptions are particularly useful for unrecoverable errors that require the system to stop completely. For example, in situations like a sudden database connection loss or a disk running out of space, the application must not proceed further and should clearly report the error. In a production company's ERP, if the database connection drops during an inventory update, the operation silently continuing could lead to disaster. In such cases, throwing a DatabaseConnectionError and catching it at the highest level to safely shut down the system both preserves data integrity and ensures the problem is quickly identified.

import logging

logging.basicConfig(level=logging.ERROR)

class DatabaseConnectionError(Exception):
    """Veritabanı bağlantı hatası."""
    pass

def connect_to_database():
    """Veritabanına bağlanmaya çalışır."""
    # Gerçekte burada bir veritabanı bağlantısı denemesi olur
    # Diyelim ki bağlantı koptu veya hiç kurulamadı
    raise DatabaseConnectionError("Veritabanı bağlantısı kurulamadı veya koptu.")

def process_order(order_id: int):
    """Sipariş işleme fonksiyonu."""
    try:
        connect_to_database()
        # Sipariş işleme mantığı burada devam eder
        print(f"Sipariş {order_id} başarıyla işlendi.")
    except DatabaseConnectionError as e:
        logging.error(f"Sipariş {order_id} işlenirken kritik veritabanı hatası oluştu: {e}")
        # Bu noktada sistemin güvenli bir şekilde kapatılması veya uyarılması gerekebilir
        raise # Hatayı yukarı fırlatmaya devam et

# Kullanım
try:
    process_order(12345)
except DatabaseConnectionError:
    print("Uygulama kritik bir hata nedeniyle durduruldu.")

Another advantage of Exceptions is that they keep the "happy path" code cleaner. When reading the normal flow of a function, error conditions are handled separately within try-except blocks. This is beneficial, especially when I want to quickly understand the business logic. However, this can also obscure the control flow; when a function's potential Exceptions aren't always explicitly stated, I might encounter unexpected errors. Last month, in the backend of my own side product, the service errored for 3 hours because I forgot to catch a rare connection error thrown by the requests library during an API call. This reminded me again that Exceptions are good for "unintended" situations but require careful handling in "expected" error scenarios.

💡 Remember

Exceptions are generally designed for "unexpected" situations or those that "disrupt the normal operation of the application." Therefore, they might be more suitable for managing systemic or infrastructural errors rather than business logic errors.

Result Types: Controlled Error Flow

Result types are an approach that has gained popularity, especially in functional programming languages (Rust, Go, Haskell) and, in recent years, in other languages (Kotlin, Swift). The basic idea is that a function returns a value upon successful completion or an error object in case of an error. Both situations are explicitly stated as part of the function's return type. For example, a value of type Result<T, E> can contain either a successful T value or an E error.

This approach enforces error management at the compiler level. This means that when a function returns a Result, the caller must check this Result and handle both success and error cases. This is a very powerful tool, especially for managing expected error scenarios within business logic. In a client project, there was an API endpoint that validated user input. Here, returning a ValidationError when invalid data was entered was much more readable and manageable than throwing Exceptions.

from typing import TypeVar, Union, Generic

T = TypeVar('T')
E = TypeVar('E')

class Success(Generic[T]):
    def __init__(self, value: T):
        self.value = value

    def is_success(self) -> bool:
        return True

    def is_failure(self) -> bool:
        return False

class Failure(Generic[E]):
    def __init__(self, error: E):
        self.error = error

    def is_success(self) -> bool:
        return False

    def is_failure(self) -> bool:
        return True

Result = Union[Success[T], Failure[E]]

class UserNotFoundError(Exception):
    def __init__(self, user_id: int):
        self.user_id = user_id
        super().__init__(f"Kullanıcı bulunamadı: {user_id}")

def get_user_by_id(user_id: int) -> Result[str, UserNotFoundError]:
    """Kullanıcı ID'sine göre kullanıcı adını döndürür."""
    if user_id % 2 == 0: # Basit bir örnek için çift ID'leri hata kabul edelim
        return Failure(UserNotFoundError(user_id))
    return Success(f"Kullanıcı Adı: user_{user_id}")

# Kullanım
user_result = get_user_by_id(101)

if user_result.is_success():
    print(f"Başarılı: {user_result.value}")
else:
    print(f"Hata: {user_result.error}")

user_result_failed = get_user_by_id(102)

if user_result_failed.is_success():
    print(f"Başarılı: {user_result_failed.value}")
else:
    print(f"Hata: {user_result_failed.error}")

The biggest advantage of Result types is that they create a safer and more understandable API by explicitly showing which errors the code can return. This is critical, especially when developing a library or service, to ensure users know all possible error conditions and handle them. In a production ERP, when performing AI-based production planning, I modeled the error codes returned by the external raw material supply chain integration using Result types. This allowed other modules using the integration to anticipate all possible error scenarios and act accordingly.

However, Result types can sometimes make code appear longer and more repetitive, especially when you need to check for errors at every step. This "error-chaining" situation can reduce code readability if not handled carefully. In some languages, operators like ? (Rust) or monadic functions like bind/map alleviate this, but in languages like Python, manual checks are more common.

My Preferences in Real Scenarios

In my 20 years of field experience, I've seen that both approaches have their unique use cases. The issue isn't really "which is better," but "which is more suitable in which situation." For me, there's a clear distinction:

  • Exceptions: I generally prefer Exceptions for unexpected, unrecoverable situations that completely disrupt the normal flow of the program. These are typically infrastructural problems, programming errors (bugs), or exceeding system limits (e.g., disk full, insufficient memory). When a systemd unit unexpectedly stops during an operation or I see a "too many messages" error in journald, that's a situation to throw a SystemException. These errors usually trigger an application shutdown or at least a serious alert mechanism.
  • Result Types: I use Result types for expected, business-logic-specific, and recoverable error scenarios. For example, a user entering invalid input, a resource not being found (404 Not Found), an authorization error (401 Unauthorized), or an API call not complying with business rules. In my Android spam blocker application, when querying whether a number is on the blacklist, I handle situations like the number not being found or hitting a service limit with Result objects. This allows me to provide specific feedback to the user on the UI side.

ℹ️ Pragmatic Approach

Both approaches are part of good engineering practice. The important thing is to choose the one that best suits your project and team's needs and to apply this choice consistently.

To give an example: When making a payment on an e-commerce site, if the credit card service becomes completely unreachable, this is an Exception. Because this situation makes it impossible for the payment process to continue and likely affects the entire payment system. However, if the credit card number is invalid or the card limit is insufficient, this is a Result type error. Because this situation is a normal response from the payment service, and a specific message like "invalid card number" can be returned to the user.

Performance and Maintenance Cost

From a performance perspective, especially in languages like Python, throwing an Exception can have a significant cost. The stack trace generation process is much slower than normal function calls. A few years ago, in a project where I was working on OOM eviction policy choices in Redis, we experienced millisecond-level performance losses due to unnecessarily thrown Exceptions in the hot path. Therefore, I use Exceptions very carefully in performance-critical code blocks.

Maintenance cost is a bit more complex:

  • Exceptions: While initially appearing to be less code, Exceptions thrown from unexpected places and not caught can lead to insidious errors in production. The debugging process, especially in a large codebase, may require carefully examining stack traces to find where an Exception originated.
  • Result Types: May require more boilerplate code, but because the error flow is clearly defined, it's clear which error conditions a function can return. This increases code readability and makes it easier for new developers to adapt to the system. While working on an internal banking platform, using Result types in financial transaction modules made error tracking and reporting much more transparent. The compiler-enforced handling of errors reduces the likelihood of erroneous situations being overlooked.

Hybrid Approach: When to Use What?

For me, the most logical approach is to use a "hybrid" model. That is, to leverage the strengths of both methods.

  1. Exceptions for Lower Layers and Infrastructural Errors: I use Exceptions for low-level components like database drivers, network connection modules, file system operations, or for truly "exceptional" (unexpected) situations. For example, a PostgreSQL connection error or an Nginx reverse proxy not responding.
  2. Result Types for Business Logic and API Layers: I prefer Result types in the service layers containing the application's business logic and in API endpoints exposed to the outside world. In these layers, it's important to explicitly state and manage business-rule-specific errors such as user input validation, authorization checks, or resource not found. This allows us to provide clearer feedback to API consumers.

This hybrid approach both preserves code cleanliness and makes error management more predictable. For example, an error in a PostgreSQL connection pool might be thrown as an Exception, which can then be caught at a higher layer, converted to a Result type, and a message like "database currently unavailable" can be communicated to the business logic.

⚠️ Things to Consider

When adopting a hybrid approach, it is crucial to establish clear rules about which error management strategy to use in which layer. Otherwise, the codebase can become complex and inconsistencies may arise.

Developer Experience and Team Standards

Error handling decisions are not just a technical preference but also affect developer experience and team productivity. Having a consistent error handling strategy within a team significantly simplifies code understanding and maintenance.

Different programming languages naturally have different error handling paradigms. For example, Rust's Result enum or Go's multiple return values (value, error) naturally support Result types, while languages like Java or C# are built around Exceptions. Python, on the other hand, allows flexible use of both approaches. I make an effort to choose based on the habits of the language and the team I'm working with. A while ago, in the backend of my anonymous Turkey data platform for my own site, I naturally adopted a model close to Result types because I was using Go.

In conclusion, error handling is not a "one size fits all" situation. Both approaches have their unique strengths and weaknesses. My clear position is: both approaches have their place; the important thing is to know when to use which and to be consistent with the team. The right error handling strategy not only catches errors but also increases system reliability and makes the development process more enjoyable. In my next post, I will share my experiences with observability (metrics/logs/traces) and how it complements error management.