Reading — step 1 of 5
Learn
Error Handling
Go made the most argued-about design decision in modern language history: no exceptions. Errors are ordinary values, returned from functions like any other result, checked with an ordinary if. You will type if err != nil ten thousand times — and in exchange, you will always know exactly which operations can fail and what happens when they do, because it's written down at every call site.
The pattern
Any function that can fail returns its result and an error, error last:
error is an interface with one method (Error() string); the only thing you need today: nil means success, non-nil means failure, and you check immediately. Not three lines later, not after using the value — immediately, because on failure the other return value is garbage you must not touch (Atoi returns 0, indistinguishable from a real zero).
The shape to internalize — Go programmers read this like punctuation:
Note the geometry: errors bail out early, success flows straight down the left margin. Go code is famous for that flat happy path — no pyramid of try/catch nesting.
Producing errors yourself
errors.New("msg") for fixed messages, fmt.Errorf when the message needs data (all the Printf verbs work). Message style is lowercase, no trailing punctuation, with context — they get wrapped and logged, and "withdraw 500: only 200 available" debugs itself.
Why values instead of exceptions?
The argument, in one paragraph: exceptions create invisible control flow — any line might throw, and nothing at the call site says so. Error values make failure part of the type signature: func Open(name string) (*File, error) tells you, in the signature, that opening can fail, the compiler makes you receive the error, and the unused-variable rule stops you from silently dropping it (you must at least write _ — a visible, greppable admission). Verbose? Yes. But you can read any Go function and see every failure path with your own eyes. (Panics exist for genuine bugs — array out of bounds, impossible states — not for expected failures like bad input. If you're reaching for panic on a parse error, reach for return err instead.)
Your exercise: Safe Parse
Read input, strconv.Atoi it, print the number if valid or an error message if not — the complete idiom, end to end. Two graded details: check err, not the value (0 is a legal parse result; only err != nil means failure), and match the expected output exactly on the failure path. TrimSpace your input if you read whole lines — an invisible \n will fail Atoi and you'll spend ten minutes learning why (a lesson everyone pays once; consider it included in tuition).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…