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

推荐订阅源

V
Vulnerabilities – Threatpost
aimingoo的专栏
aimingoo的专栏
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
Engineering at Meta
Engineering at Meta
IT之家
IT之家
V
Visual Studio Blog
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
A
About on SuperTechFans
博客园 - 聂微东
Blog — PlanetScale
Blog — PlanetScale
N
News and Events Feed by Topic
A
Arctic Wolf
WordPress大学
WordPress大学
小众软件
小众软件
C
CERT Recently Published Vulnerability Notes
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Y
Y Combinator Blog
T
Threat Research - Cisco Blogs
Latest news
Latest news
Simon Willison's Weblog
Simon Willison's Weblog
Cyberwarzone
Cyberwarzone
S
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
Lohrmann on Cybersecurity
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
J
Java Code Geeks
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
I
Intezer
L
LangChain Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
GRAHAM CLULEY
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News and Events Feed by Topic
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
Security Archives - TechRepublic
Security Archives - TechRepublic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

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
The Bilingual Developer: Python and Go, The Error Handling Paradigm
Ezeana Micheal · 2026-06-27 · via DEV Community

In the previous article, we explored how functions allow us to package logic into reusable blocks. However, a crucial question remains: what happens when that logic goes wrong?

Building applications is not just about writing code for the "happy path," the scenario where everything works perfectly. In reality, our programs interact with the messy, unpredictable outside world. Files we try to open might be missing. Network connections might timeout. Databases might be overloaded. Disk drives might fill up mid-write.

If we ignore these possibilities, our applications will crash spectacularly, leaving users frustrated and data corrupted.

Therefore, a programming language must provide a clear, disciplined way to predict, handle, and recover from failures. This is where Python and Go diverge in one of the most profound ways possible. They represent two completely different schools of thought on how to manage errors. Python embraces the Exception Model, using structured "try/catch" blocks to intercept errors thrown from anywhere. Go rejects exceptions in favor of Errors as Values, forcing developers to handle errors immediately and explicitly by checking return values. Furthermore, when it comes to cleaning up resources (like closing files or releasing network connections), Python offers the elegant with statement (Context Managers), while Go provides the powerful and unique defer keyword.

The Python Way: The Exception Model

Python operates on a philosophy known as EAFP, which stands for "Easier to Ask for Forgiveness than Permission." This is a distinctly optimistic approach. In Python, you write the code you expect to work, and if something bad happens, the program "raises" (or throws) an exception that interrupts the normal flow of execution.

Think of an exception like a fire alarm. When everything is fine, the alarm is silent, and your program runs smoothly. But when a fire starts (an error occurs), the alarm blares. If you have a fire suppression system (except block) ready, you can contain and handle the fire. If you don't, the fire spreads up the chain of command until the whole building (the program) burns down and crashes.

The try / except / else / finally Structure

Python provides a layered structure to manage exceptions. The try block contains the code that might fail. The except block catches specific errors. The else block runs only if no errors occurred, and the finally block runs regardless of what happened—it is the cleanup crew.

Consider this example where we ask a user for a number:

try:  
    user_input = input("Enter a number: ")  
    number = int(user_input)  # This might raise a ValueError  
    result = 100 / number     # This might raise a ZeroDivisionError  
except ValueError:  
    print("Oops! That wasn't a valid number.")  
except ZeroDivisionError:  
    print("You can't divide by zero!")  
else:  
    print(f"The calculation succeeded! Result: {result}")  
finally:  
    print("Thanks for using the calculator.")  

If the user types "five", the ValueError is caught, and the program prints a friendly message instead of crashing. Crucially, the finally block always executes, ensuring that no matter what happens, we can close a file or log the attempt.

The Nature of Python Exceptions

One of the defining characteristics of Python's model is that exceptions bubble up. If you don't catch an exception in the function where it occurs, it automatically propagates up to the function that called it, then up to the next, and so on, until it either finds a matching except block or terminates the entire process.

This allows developers to write very clean, readable "happy path" code. The error-handling logic is neatly separated from the business logic. However, this convenience has a dark side. It is entirely possible to write Python code that "swallows" exceptions by catching a generic Exception and doing nothing, or to forget to handle an edge case entirely, leading to unexpected production crashes. Python trusts the developer to be disciplined, but it does not enforce that discipline at the language level.

The Go Way: Errors as Values

If Python's philosophy is optimistic and permissive, Go's philosophy is stoic, pragmatic, and hyper-vigilant. Go explicitly rejects the exception model (with the exception of panic, which is reserved for catastrophic, unrecoverable events). Instead, Go treats errors as first-class values—just like strings, integers, or booleans.

In Go, if a function can fail, it returns an error as part of its standard return signature. The burden of checking for that error falls squarely on the caller. There is no implicit bubbling up of exceptions; the error is just a piece of data passed from one function to another.

Think of it like a pilot going through a pre-flight checklist. At every single step: checking fuel, checking the flaps, checking the radar, the pilot looks at the instrument panel and asks: "Is everything okay?" If at any point the dial reads "Error," the pilot must stop and address it immediately before moving to the next step.

The Ubiquitous if err != nil

The idiomatic pattern in Go is so ingrained that it has become a meme in the developer community. It looks like this:

package main  
import (  
    "errors"  
    "fmt"  
)

func divide(a int, b int) (int, error) {  
    if b == 0 {  
        return 0, errors.New("cannot divide by zero")  
    }  
    return a / b, nil  
}

func main() {  
    result, err := divide(10, 0)  
    if err != nil {  
        fmt.Println("Handled error:", err) // Output: Handled error: cannot divide by zero  
    } else {  
        fmt.Println("Result:", result)  
    }  
}  

Notice the pattern: result, err := divide(...). Immediately following that line is an if statement checking if err != nil.

This design forces the developer to confront the possibility of failure at the exact moment it occurs. You cannot ignore the error, because the compiler won't stop you from ignoring it, but the language syntax encourages you to handle it right there.

The Beauty of Verbosity

Many new developers look at Go's if err != nil blocks and complain about verbosity(which I personally enjoy it). A simple 5-line function might have 3 lines dedicated to error handling.

However, this verbosity is an intentional feature, not a bug. By making error handling explicit and visibly "in your face," Go ensures that the state of the program is always known. When you read Go code, you can trace the exact path the data takes. You can see exactly where a function might exit early due to a failure.

This eliminates the surprise element found in Python. In Go, you never have to guess if an underlying library is going to throw a random exception 12 layers deep. The language is brutally honest: every possible failure is declared in the function signature, and every caller is forced to deal with it.

Cleanup and Resource Management: with vs. defer

Handling errors is only half the battle. Often, when an error occurs, we have to gracefully clean up the mess. For example, if you open a file, you must close it. If you lock a mutex, you must unlock it. If a network connection is established, it must be gracefully terminated. Both Python and Go offer sophisticated tools for resource cleanup, but they operate on entirely different scopes.

Python’s Context Managers (with statement)

Python manages resources through the with statement, which leverages the concept of Context Managers.

A context manager is an object that defines two magic methods: enter (executed at the start of the block) and exit (executed when the block finishes, even if an exception occurred).

Consider the classic example of reading a file:

with open("data.txt", "r") as file:  
    content = file.read()

    # The file is automatically closed when the 'with' block ends  
# The file is guaranteed to be closed here, regardless of exceptions in file.read()  

The with statement brilliantly bundles acquisition and release into a single, readable line. The exit method handles the cleanup, ensuring the file pointer is closed, database connections are committed, or locks are released the moment you leave the indented block.

The beauty here is scope control. The resource exists only within the boundaries of the with block. This makes Python code highly readable and safe, as long as the developer remembers to use the context manager rather than manually opening and closing files.

Go’s Deferred Functions (defer keyword)

Go does not have a built-in with statement. Instead, it introduces a deceptively simple yet incredibly powerful keyword: defer.

When you prefix a function call with defer, Go schedules that function to run just before the surrounding function returns. It doesn't matter whether the function returns normally, hits a return statement early, or encounters a panic and crashes—the defered call will always execute.

func ReadFile(filename string) error {  
    file, err := os.Open(filename)  
    if err != nil {  
        return err  
    }

    // Defer ensures this runs when the function exits,   
    // regardless of what happens below.  
    defer file.Close() 

    // Perform some operations on the file...  
    data := make([]byte, 100)  
    _, err = file.Read(data)  
    if err != nil {  
        // Even if we return an error here, file.Close() still runs!  
        return err  
    }  
    // If we reach the end, file.Close() still runs!  
    return nil  
}  

Notice that defer file.Close() is written immediately after the file is successfully opened. This keeps the resource management right next to the resource allocation, making it easy for developers to see the pairing.

The Power of Stacked defer

Go allows you to defer multiple functions. When you do this, they execute in Last In, First Out (LIFO) order—essentially a stack.

func main() {  
    defer fmt.Println("Third") // Runs last  
    defer fmt.Println("Second") // Runs second  
    defer fmt.Println("First") // Runs first  
}

// Output:  
// First  
// Second  
// Third  

This is exceptionally useful when dealing with complex resources like nested locks or database transactions. If you acquire a read lock, then a write lock, defer ensures they are released in the correct reverse order, preventing deadlocks.

The Philosophical Head-to-Head

Let's boil down the key differences to understand the mindsets behind each language.

Python's Philosophy: "You are a responsible adult."

  • Errors: Exceptions are for exceptional, unexpected cases. We trust you to handle them with try/except, but if you miss one, the interpreter will tell you.
  • Cleanup: We provide elegant, block-level tools (with) to ensure resources are cleaned up as soon as you logically leave the context.
  • Result: Code is compact, readable, and fast to write. The main logic isn't cluttered with constant checks.

Go's Philosophy: "Murphy's Law is absolute."

  • Errors: Errors are just data. They are not exceptional; they are an expected part of every operation. You must check each one explicitly.
  • Cleanup: We provide function-level tools (defer). The scope is the entire function, ensuring cleanup happens no matter how complex the logic gets.
  • Result: Code is verbose, bulletproof, and explicit. There is no magic. You can trace exactly what happens at every single line of execution.

Final Thoughts

The error handling paradigm of a language reveals its soul.

When you code in Python, you write in a trusting environment*. You focus on solving the problem, knowing that if something goes wrong, an exception will give you a very clear stack trace to debug it. It is forgiving, which accelerates prototyping and iteration. **The with statement adds a layer of syntactic sugar that makes resource management almost pleasurable.*

When you code in Go*, you write in a defensive environment.* You are constantly asking, "What if this fails?" You check err != nil religiously. It feels pedantic at first, but over time, it cultivates a profound sense of reliability. By using defer, you ensure that your cleanup is tied to the lifetime of the function, making it incredibly hard to leak resources.

A Python developer moving to Go might initially feel frustrated by the verbosity. But the truth is, Go forces you to be honest about the fragility of the systems you are building. In distributed systems, where network calls fail constantly, the "just let it crash" or "ask for forgiveness" model can be dangerous. Go's explicit model, combined with defer, builds software that is designed to withstand the chaos of the real world.

Mastering both paradigms gives you the wisdom to choose the right tool for the job. For a quick script, Python's exceptions are a lifesaver. For a critical backend server that must run for years without downtime, Go's rigorous error values and cleanup mechanisms are the gold standard.