Go error handling programs show how Go reports and deals with problems, such as a missing file, bad input or a failed payment. Go has no exceptions: functions return an error value, and you check it right away. In this post, you will write fourteen error handling programs with their exact output, covering custom errors, wrapping, errors.Is, errors.As, errors.Join, panic and recover, followed by the error questions interviewers ask most.
This post builds on our Go interface programs, because error is an interface. For the theory, read the Go error handling guide, Go error wrapping and Go defer, panic and recover. All programs were tested on Go 1.27.
What are Go Error Handling Programs?
Go error handling programs return an error as the last result of a function. If the error is nil, everything worked. If it is not nil, the caller decides what to do: retry, add context, return it up, or show a message.
Think of a delivery app. When the rider cannot find the address, the app does not crash. It shows “address not found” and lets you fix it. Go errors work the same way: they are normal values that carry a message back to whoever can fix the problem.
Why Go Error Handling Programs Matter
Every real program meets errors: files go missing, networks fail and users type bad data. Go makes these failures visible in the code, so you cannot ignore them by accident. Good Go error handling programs give clear messages and still let callers check what went wrong.
- Reliability: checking errors stops bad data from spreading.
- Debugging: wrapped errors show the full path of a failure.
- Interviews:
errors.Isvserrors.As, panic vs error and the nil error trap are common questions.
How Go Error Handling Programs Work
A function returns (result, error). The caller checks if err != nil straight after the call. To add context, it wraps the error with fmt.Errorf("...: %w", err) and returns it. Higher up, code uses errors.Is or errors.As to look inside the chain.

The table below lists the error tools in this post.
| Tool | What it does | Since |
|---|---|---|
| errors.New(“msg”) | Creates a simple error | Always |
| fmt.Errorf(“ctx: %w”, err) | Wraps an error with context | Go 1.13 |
| errors.Is(err, target) | Checks for a specific error in the chain | Go 1.13 |
| errors.As(err, &target) | Finds an error of a given type | Go 1.13 |
| errors.Unwrap(err) | Gets the next error in the chain | Go 1.13 |
| errors.Join(e1, e2) | Combines several errors | Go 1.20 |
| panic / recover | Handles truly unexpected failures | Always |
Basic Go Error Handling Programs
These first Go error handling programs create and check errors.
Program 1: errors.New, the Start of All Go Error Handling Programs
Start with the smallest idea. A function returns an error when something is wrong, and nil when all is fine.
package main
import (
"errors"
"fmt"
)
// checkAge returns an error if the age is below zero.
func checkAge(age int) error {
if age < 0 {
return errors.New("age cannot be negative") // errors.New makes a simple error
}
return nil // nil means "no error"
}
func main() {
err := checkAge(25) // err is the error value
fmt.Println("Check 25:", err)
err = checkAge(-3)
if err != nil { // the usual Go check
fmt.Println("Check -3 failed:", err)
}
}
Check 25: <nil>
Check -3 failed: age cannot be negative
checkAge has error as its return type. For 25 it returns nil, which prints as <nil>. For -3 it returns an error, so the if err != nil block runs and prints the message.
Program 2: Return and Check an Error
package main
import (
"errors"
"fmt"
)
// withdraw takes money out and returns the new balance, or an error.
func withdraw(balance, amount int) (int, error) {
if amount > balance {
return balance, errors.New("insufficient balance") // keep the old balance
}
return balance - amount, nil
}
func main() {
balance, err := withdraw(1000, 300)
fmt.Println(balance, err)
balance, err = withdraw(balance, 900) // = reuses the variables, := would make new ones
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Balance:", balance)
}
700 <nil>
Error: insufficient balance
Balance: 700
The function returns two values: the balance and an error. We return the old balance with the error, so the caller still has a sensible value. The if err != nil check comes right after the call.
Program 3: Sentinel Errors with errors.Is
A sentinel error is a named error value that callers can check for.
package main
import (
"errors"
"fmt"
)
// ErrNotFound is a named error that callers can compare against.
var ErrNotFound = errors.New("user not found")
// findUser returns the name for an ID, or ErrNotFound.
func findUser(id int) (string, error) {
users := map[int]string{1: "Asha", 2: "Ravi"}
name, ok := users[id] // ok is true if the ID is in the map
if !ok {
return "", ErrNotFound
}
return name, nil
}
func main() {
for _, id := range []int{1, 7} {
name, err := findUser(id)
if errors.Is(err, ErrNotFound) { // is this our "not found" error?
fmt.Println(id, "-> please sign up")
continue // skip to the next ID
}
fmt.Println(id, "->", name)
}
}
1 -> Asha
7 -> please sign up
ID 1 is in the map, so it prints the name. ID 7 is missing, so findUser returns ErrNotFound. Callers compare with errors.Is instead of matching the message text, so you can change the wording later.
Program 4: Wrap Errors with %w
package main
import (
"errors"
"fmt"
)
// ErrTimeout is the low-level error.
var ErrTimeout = errors.New("timeout")
// callBank always fails in this example.
func callBank() error {
return ErrTimeout
}
// processPayment adds the order ID to any error from callBank.
func processPayment(orderID int) error {
err := callBank()
if err != nil {
return fmt.Errorf("payment for order %d: %w", orderID, err) // %w wraps the original error
}
return nil
}
func main() {
err := processPayment(501)
fmt.Println(err)
fmt.Println(errors.Is(err, ErrTimeout)) // look inside the wrapper
fmt.Println(errors.Unwrap(err) == ErrTimeout) // Unwrap removes one layer
}
payment for order 501: timeout
true
true
%w keeps the original error inside the new one. So the message gains context, and errors.Is can still find ErrTimeout. errors.Unwrap takes off the outer layer and gives back the original.
Custom Go Error Handling Programs
In Go error handling programs, custom error types carry extra details that callers can use.
Program 5: A Custom Error Type with errors.As
package main
import (
"errors"
"fmt"
)
// ValidationError says which field is wrong and why.
type ValidationError struct {
Field string
Issue string
}
// Error makes *ValidationError satisfy the error interface.
func (validationError *ValidationError) Error() string {
return validationError.Field + ": " + validationError.Issue
}
// register checks the age and returns a wrapped ValidationError.
func register(email string, age int) error {
if age < 18 {
problem := &ValidationError{"age", "must be 18 or older"}
return fmt.Errorf("register: %w", problem)
}
return nil
}
func main() {
err := register("asha@example.com", 16)
var target *ValidationError // errors.As will fill this in
if errors.As(err, &target) { // pass the address so As can store the result
fmt.Println("Field:", target.Field)
fmt.Println("Issue:", target.Issue)
}
fmt.Println(err)
}
Field: age
Issue: must be 18 or older
register: age: must be 18 or older
errors.As walks the chain and fills target when it finds a *ValidationError. Then you can read its fields, which a plain string could never give you.
Program 6: Combine Errors with errors.Join
package main
import (
"errors"
"fmt"
"strings"
)
// ErrEmpty is returned when the name is blank.
var ErrEmpty = errors.New("name is empty")
// validate collects every problem instead of stopping at the first one.
func validate(name, email string) error {
var problems []error // starts empty
if name == "" {
problems = append(problems, ErrEmpty)
}
if !strings.Contains(email, "@") {
problems = append(problems, fmt.Errorf("email %q is invalid", email))
}
return errors.Join(problems...) // ... passes each item in the slice
}
func main() {
err := validate("", "asha.example.com")
fmt.Println(err)
fmt.Println(errors.Is(err, ErrEmpty))
fmt.Println(validate("Asha", "a@b.com") == nil)
}
name is empty
email "asha.example.com" is invalid
true
true
validate adds each problem to a slice, then joins them into one error. errors.Join puts each error on its own line. It returns nil when the list is empty, so a valid form gives no error at all.
Program 7: Print the Whole Error Chain
package main
import (
"errors"
"fmt"
)
func main() {
// Step 1: build three layers of errors.
diskError := errors.New("disk full")
saveError := fmt.Errorf("save invoice: %w", diskError)
checkoutError := fmt.Errorf("checkout: %w", saveError)
// Step 2: print each layer, from the outside in.
current := checkoutError
for current != nil {
fmt.Println("-", current)
current = errors.Unwrap(current) // move one layer down; nil at the bottom
}
}
- checkout: save invoice: disk full
- save invoice: disk full
- disk full
Each Unwrap call peels off one layer. The loop stops when there is nothing left, because Unwrap returns nil. This is a handy way to see how a deep error reached the top.
Real-World Go Error Handling Programs
These Go error handling programs deal with files, input and retries.
Program 8: File Not Found with fs.ErrNotExist
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
_, err := os.Open("missing-report.txt") // _ ignores the file, we only need err
// Is this a "file does not exist" error?
if errors.Is(err, fs.ErrNotExist) {
fmt.Println("File does not exist, creating a new one")
}
// Get the detailed path error to read its fields.
var pathError *fs.PathError
if errors.As(err, &pathError) {
fmt.Println("Operation:", pathError.Op, "Path:", pathError.Path)
}
}
File does not exist, creating a new one
Operation: open Path: missing-report.txt
os.Open fails because the file is missing. The standard library wraps its errors too. So the same errors.Is and errors.As tools work on file and network errors.
Program 9: Convert Text to a Number Safely
This is an error you will meet on day one. The text may not be a number at all.
package main
import (
"fmt"
"strconv"
)
func main() {
for _, text := range []string{"42", "abc"} {
number, err := strconv.Atoi(text) // Atoi turns text into an int
if err != nil {
fmt.Println("Not a number:", text)
continue
}
fmt.Println("Got the number", number)
}
}
Got the number 42
Not a number: abc
strconv.Atoi returns a number and an error. For “42” the error is nil, so you can use the number. For “abc” it returns an error, and the program prints a friendly message instead of crashing.
Program 10: Parse Input and Report Bad Values
package main
import (
"fmt"
"strconv"
)
// parseAges turns a list of texts into ages, or says which item is bad.
func parseAges(input []string) ([]int, error) {
var ages []int
for i, text := range input { // i is the position, text is the value
age, err := strconv.Atoi(text)
if err != nil {
return nil, fmt.Errorf("item %d: %w", i, err) // say which item failed
}
ages = append(ages, age)
}
return ages, nil
}
func main() {
fmt.Println(parseAges([]string{"21", "34", "19"}))
fmt.Println(parseAges([]string{"21", "thirty", "19"}))
}
[21 34 19] <nil>
[] item 1: strconv.Atoi: parsing "thirty": invalid syntax
The loop converts each text and stops at the first bad one. The error tells you exactly which item failed and why. This kind of message saves a lot of debugging time.
Program 11: Retry on a Temporary Error
package main
import (
"errors"
"fmt"
)
// ErrBusy means "try again later".
var ErrBusy = errors.New("server busy")
// Server fails the first two calls, then works.
type Server struct {
attempts int // how many times Call has run
}
// Call counts the attempt and returns ErrBusy until the third try.
func (server *Server) Call() error {
server.attempts++
if server.attempts < 3 {
return ErrBusy
}
return nil
}
func main() {
server := &Server{}
for try := 1; try <= 5; try++ {
err := server.Call()
if err == nil {
fmt.Println("Success on try", try)
break // stop the loop, we are done
}
if errors.Is(err, ErrBusy) {
fmt.Println("Try", try, "failed:", err)
}
}
}
Try 1 failed: server busy
Try 2 failed: server busy
Success on try 3
The loop calls the server up to five times. The first two calls return ErrBusy, so we print and try again. On the third call the error is nil, and break ends the loop. In real code, you would also wait a little longer before each new try.
Panic and Recover in Go Error Handling Programs
panic stops normal flow, and recover inside a deferred function can catch it. Use them only for real bugs or impossible states, not for normal errors.
Program 12: Recover from a Panic
package main
import "fmt"
// safeDivide divides two numbers and turns a panic into an error.
func safeDivide(dividend, divisor int) (result int, err error) { // named results
// defer runs this function when safeDivide ends, even after a panic.
defer func() {
recovered := recover() // nil if there was no panic
if recovered != nil {
err = fmt.Errorf("recovered: %v", recovered)
}
}()
return dividend / divisor, nil // dividing by 0 panics here
}
func main() {
fmt.Println(safeDivide(10, 2))
fmt.Println(safeDivide(10, 0))
fmt.Println("program keeps running")
}
5 <nil>
0 recovered: runtime error: integer divide by zero
program keeps running
Dividing by zero causes a panic. The deferred function catches it with recover and turns it into a normal error by setting the named result err. Without recover, the whole program would crash.
Program 13: Defers Still Run During a Panic
package main
import "fmt"
// work sets up two cleanups, then panics.
func work() {
defer fmt.Println("cleanup: close file") // runs second
defer fmt.Println("cleanup: release lock") // runs first (last in, first out)
panic("something went badly wrong")
}
func main() {
defer func() {
fmt.Println("main recovered:", recover())
}()
work()
fmt.Println("never printed") // the panic skips this line
}
cleanup: release lock
cleanup: close file
main recovered: something went badly wrong
As the panic travels up, every deferred call runs in reverse order. Then main catches the panic with recover. That is why defer is the right place for cleanup.
Program 14: Must Functions Panic on Setup Errors
package main
import (
"fmt"
"regexp"
)
func main() {
// MustCompile panics if the pattern is wrong; fine for fixed patterns.
pinPattern := regexp.MustCompile(`^\d{6}$`) // exactly six digits
fmt.Println(pinPattern.MatchString("411001"), pinPattern.MatchString("4110"))
// Compile returns an error instead of panicking.
_, err := regexp.Compile(`[a-z`)
fmt.Println(err)
}
true false
error parsing regexp: missing closing ]: `[a-z`
MustCompile is safe here because the pattern is fixed in the code. Must functions are for values like this, where a mistake is a bug you want to see at once. For user input, use the version that returns an error.
Errors vs Panic in Go Error Handling Programs
Every one of the Go error handling programs above makes one choice. The diagram and table below show when to return an error and when to panic.

| Feature | Return an error | panic |
|---|---|---|
| Used for | Expected problems | Bugs and impossible states |
| Example | File missing, bad input | Nil map write, broken setup |
| Caller sees it | In the return value | Only through recover |
| Program keeps running | Yes | No, unless recovered |
| Normal in libraries | Yes | Rarely, avoid it |
In short, return errors for anything a user or the network can cause. Panic only when continuing would be worse than stopping.
Common Mistakes in Go Error Handling Programs
- Ignoring errors with _: a skipped error often turns into a confusing bug later.
- Using %v instead of %w:
%vloses the original error, soerrors.Isstops working. - Comparing message strings: wording can change, so compare with
errors.Isorerrors.As. - Returning a typed nil pointer as error: an interface holding a nil pointer is not nil.
- Using panic for normal failures: callers cannot handle it with a simple
if.
Best Practices for Go Error Handling Programs
- Check errors right after the call, before you use the result.
- Add context when you return, such as
fmt.Errorf("load config: %w", err). - Use sentinel errors or custom types for errors callers need to check.
- Handle each error once: either log it or return it, not both.
- Keep error messages lower case and without a full stop, as Go style suggests.
Go Error Handling Programs Interview Questions and Answers
Interviewers ask these Go error handling programs more than any other error questions. Each program is complete, with real output from Go 1.27.
Error Basics Questions
Q1. What is the error type in Go?
It is a built-in interface with one method: Error() string. Any type with that method can be used as an error.
Q2. Why does Go not have exceptions?
Go treats errors as normal values, so the code shows every place that can fail. This makes failure paths easy to read and test. panic exists, but only for truly exceptional cases.
Q3. What is the difference between errors.Is and errors.As?
errors.Is checks whether a specific error value, such as ErrNotFound, is in the chain. errors.As looks for an error of a specific type and gives you that value, so you can read its fields.
Wrapping Questions
Q4. What does this program print?
package main
import (
"errors"
"fmt"
)
// ErrLimit is the original error.
var ErrLimit = errors.New("limit reached")
func main() {
withV := fmt.Errorf("upload: %v", ErrLimit) // %v copies only the text
withW := fmt.Errorf("upload: %w", ErrLimit) // %w keeps the original error inside
fmt.Println(withV, "|", withW)
fmt.Println(errors.Is(withV, ErrLimit), errors.Is(withW, ErrLimit))
}
upload: limit reached | upload: limit reached
false true
Both messages look the same. But only %w keeps the original error inside, so only withW passes the errors.Is check.
Q5. What does this program print?
package main
import (
"errors"
"fmt"
)
func main() {
first := errors.New("same text")
second := errors.New("same text")
fmt.Println(first == second, first.Error() == second.Error()) // compare the values, then the texts
}
false true
Each errors.New call creates a new, unique value. Two errors with the same text are still different errors, which is why sentinels are declared once as package variables.
Q6. Can you wrap more than one error with fmt.Errorf?
Yes. Since Go 1.20, you can use %w more than once in the same format string. Then errors.Is matches any of the wrapped errors.
package main
import (
"errors"
"fmt"
)
// Two separate sentinel errors.
var ErrDisk = errors.New("disk failed")
var ErrNetwork = errors.New("network failed")
func main() {
err := fmt.Errorf("both: %w and %w", ErrDisk, ErrNetwork) // wrap both at once
fmt.Println(err)
fmt.Println(errors.Is(err, ErrDisk), errors.Is(err, ErrNetwork))
}
both: disk failed and network failed
true true
The message joins both texts. Because both were wrapped with %w, errors.Is finds each of them.
Panic and Recover Questions
Q7. Where does recover work?
Only inside a deferred function, while a panic is happening. Called anywhere else, recover returns nil and does nothing.
Q8. What does this program print?
package main
import "fmt"
func main() {
fmt.Println(recover()) // no panic yet, so this prints nil
defer func() {
recovered := recover() // catches the panic below
fmt.Println("caught:", recovered)
}()
var scores map[string]int // a nil map, never made with make
scores["asha"] = 1 // writing to a nil map panics
}
<nil>
caught: assignment to entry in nil map
The first recover runs outside a panic, so it returns nil. The deferred one catches the nil map panic.
Q9. Does a panic in one goroutine get caught by recover in main?
No. recover only works in the same goroutine that panicked. Each goroutine that might panic needs its own deferred recover, or the whole program crashes.
Output Questions
Q10. What does this program print?
package main
import (
"errors"
"fmt"
)
// CodeError carries an HTTP status code.
type CodeError struct{ Code int }
// Error uses a value receiver.
func (codeError CodeError) Error() string { return fmt.Sprintf("code %d", codeError.Code) }
func main() {
err := fmt.Errorf("api: %w", CodeError{404})
var target CodeError
if errors.As(err, &target) { // &target lets As fill in the value
fmt.Println("status", target.Code)
}
}
status 404
Here the custom error uses a value receiver, so we pass a pointer to a CodeError variable. errors.As needs a pointer to the target so it can fill it.
Q11. What does this program print?
package main
import (
"errors"
"fmt"
)
// check returns an error for negative numbers, with extra context added by defer.
func check(number int) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("check(%d): %w", number, err) // add context on the way out
}
}()
if number < 0 {
return errors.New("negative")
}
return nil
}
func main() {
fmt.Println(check(5))
fmt.Println(check(-1))
}
<nil>
check(-1): negative
A deferred function can add context to every error a function returns, using the named err result. This keeps each return short.
Q12. Should you log an error and also return it?
Usually no. Doing both causes the same error to appear many times in the logs. Return it with context, and log it once at the top, where you decide what to do.
Practice Task
A money transfer is a classic among Go error handling programs. Write a transfer(from, to *Account, amount int) error function that returns a wrapped ErrInsufficientFunds sentinel when the balance is too low, and a *ValidationError when the amount is zero or negative. In main, use errors.Is and errors.As to print a friendly message for each case. Hint: wrap with %w so both checks still work.
Official Resources
- errors package documentation
- Working with errors in Go 1.13 (Go blog)
- Defer, panic and recover (Go blog)
Quick Recap
- Go error handling programs return
erroras the last result and check it withif err != nil. - Wrap errors with
fmt.Errorfand%wso context is added and the original is kept. - Use
errors.Isfor specific error values anderrors.Asfor error types. errors.Joincombines several errors, and%wcan appear more than once.- Use panic only for bugs, and recover only inside deferred functions.
What’s Next?
Next, we finish Level 4 with dates and times. Read Go date and time programs with output, with formatting, durations, an age calculator and time zones. For more practice, see the Go error handling interview questions.


