Error Handling — Learning to Love `if err != nil`
Error Handling — Learning to Love if err != nil In part 3 I covered goroutines and channels, and how Go's concurrency model sidesteps a lot of the ceremony I was used to from the JVM. This time I'm tackling the thing I complained about in part 1 of this series before I'd even really tried it: error handling. I called if err != nil repetitive back then. A few weeks and a lot of real code later, I owe Go a partial apology. No Exceptions, On Purpose Coming from Java, the absence of try / catch is the first thing that feels like a missing feature. It isn't — it's a deliberate design choice. In Go, errors are just values. A function that can fail returns an error as its last return value, and the caller decides what to do with it, right there, inline: func divide ( a , b float64 ) ( float64 , error ) { if b == 0 { return 0 , errors . New ( "division by zero" ) } return a / b , nil } func main () { result , err := divide ( 10 , 0 ) if err != nil { fmt . Println ( "error:" , err ) return } fmt . Println ( "result:" , result ) } That's the pattern you'll write hundreds of times in Go: call a function, check err , handle it or bail out, move on. No hidden control flow jumping up the call stack to whichever catch block happens to match. No checked-exception signatures cluttering method declarations. No RuntimeException quietly skipping past five layers of code that had no idea it could happen. Whatever can fail is sitting right there in the function signature, and you're forced to look at it. Why the Repetition Is the Point My part 1 complaint was that if err != nil everywhere feels manual. It is manual — and that's exactly the trade Go is making. In Java, an exception thrown deep in a call stack can silently propagate through layers of code that never declared they might fail, and you only find out where things actually break by reading a stack trace after the fact. In Go, every single point where something can go wrong is visible in the source, in order, as you read top to