Bird
Raised Fist0
Goprogramming~20 mins

Handling errors in Go - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Error Handling Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of error handling with multiple returns
What is the output of this Go program when the function returns an error?
Go
package main

import (
	"errors"
	"fmt"
)

func checkValue(val int) (string, error) {
	if val < 0 {
		return "", errors.New("negative value")
	}
	return "Value is positive", nil
}

func main() {
	msg, err := checkValue(-5)
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println(msg)
	}
}
ACompilation error
BValue is positive
CError: <nil>
DError: negative value
Attempts:
2 left
💡 Hint
Check what the function returns when the input is negative.
❓ Predict Output
intermediate
2:00remaining
Result of deferred function with error handling
What will be printed by this Go program?
Go
package main

import "fmt"

func main() {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("Deferred error:", err)
		} else {
			fmt.Println("No error")
		}
	}()
	err = fmt.Errorf("something went wrong")
	fmt.Println("Main function running")
}
A
Main function running
No error
B
Main function running
Deferred error: something went wrong
C
Deferred error: something went wrong
Main function running
DCompilation error
Attempts:
2 left
💡 Hint
Remember when deferred functions run and the value of err at that time.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in error handling
What runtime error will this Go program produce?
Go
package main

import (
	"errors"
	"fmt"
)

func riskyOperation() error {
	return errors.New("operation failed")
}

func main() {
	var err error
	err = riskyOperation()
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("Operation succeeded")
}
Apanic: operation failed
BOperation succeeded
CCompilation error: missing import
DNo output
Attempts:
2 left
💡 Hint
Check what happens when panic is called with an error message.
🧠 Conceptual
advanced
2:00remaining
Understanding error wrapping and unwrapping
Given the following code, what will be the output?
Go
package main

import (
	"errors"
	"fmt"
)

func main() {
	baseErr := errors.New("base error")
	wrappedErr := fmt.Errorf("wrapped: %w", baseErr)

	if errors.Is(wrappedErr, baseErr) {
		fmt.Println("Error matches base error")
	} else {
		fmt.Println("Error does not match")
	}
}
AError matches base error
BError does not match
CCompilation error: invalid format verb
DNo output
Attempts:
2 left
💡 Hint
Look at how %w is used in fmt.Errorf and how errors.Is works.
❓ Predict Output
expert
3:00remaining
Output of concurrent error handling with channels
What will this Go program print?
Go
package main

import (
	"errors"
	"fmt"
	"sync"
)

func worker(id int, ch chan error, wg *sync.WaitGroup) {
	defer wg.Done()
	if id%2 == 0 {
		ch <- nil
	} else {
		ch <- errors.New(fmt.Sprintf("error from worker %d", id))
	}
}

func main() {
	ch := make(chan error, 5)
	var wg sync.WaitGroup

	for i := 1; i <= 5; i++ {
		wg.Add(1)
		go worker(i, ch, &wg)
	}

	wg.Wait()
	close(ch)

	countErrors := 0
	for err := range ch {
		if err != nil {
			fmt.Println(err.Error())
			countErrors++
		}
	}
	fmt.Println("Total errors:", countErrors)
}
ADeadlock error
B
error from worker 2
error from worker 4
Total errors: 2
C
error from worker 1
error from worker 3
error from worker 5
Total errors: 3
DTotal errors: 0
Attempts:
2 left
💡 Hint
Check which workers send errors and which send nil, and how many errors are counted.

Practice

(1/5)
1. In Go, how do you check if a function returned an error?
easy
A. By checking if the error variable is zero
B. By checking if the error variable is an empty string
C. By checking if the error variable equals false
D. By checking if the error variable is not nil

Solution

  1. Step 1: Understand error type in Go

    Errors in Go are values, and when a function returns an error, it returns a value of type error or nil if no error occurred.
  2. Step 2: Check error value

    To know if an error happened, you check if the error variable is not nil, meaning an error value exists.
  3. Final Answer:

    By checking if the error variable is not nil -> Option D
  4. Quick Check:

    error != nil = true means error occurred [OK]
Hint: Always check if error != nil to detect errors [OK]
Common Mistakes:
  • Checking error == 0 instead of error != nil
  • Assuming error is a boolean
  • Comparing error to empty string
2. Which of the following is the correct way to declare and check an error returned by a function doTask() in Go?
easy
A. error := doTask() if error != false { // handle error }
B. err := doTask() if err != nil { // handle error }
C. err := doTask() if err == 0 { // handle error }
D. var err doTask() if err == nil { // handle error }

Solution

  1. Step 1: Declare error variable correctly

    Use short variable declaration with := to assign the error returned by doTask() to err.
  2. Step 2: Check if error is not nil

    Use if err != nil to check if an error occurred and handle it inside the block.
  3. Final Answer:

    err := doTask() if err != nil { // handle error } -> Option B
  4. Quick Check:

    Use := and err != nil for error handling [OK]
Hint: Use err := func() and check err != nil [OK]
Common Mistakes:
  • Using wrong variable declaration syntax
  • Checking error against 0 or false
  • Using reserved word 'error' as variable name
3. What will be the output of this Go code?
package main
import (
    "errors"
    "fmt"
)
func divide(a, b int) (int, 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(err)
    } else {
        fmt.Println(result)
    }
}
medium
A. division by zero
B. 0
C. 10
D. runtime error

Solution

  1. Step 1: Analyze divide function behavior

    If b is zero, divide returns 0 and an error with message "division by zero".
  2. Step 2: Check main function output

    Since divide(10, 0) returns an error, err != nil is true, so fmt.Println(err) prints the error message.
  3. Final Answer:

    division by zero -> Option A
  4. Quick Check:

    Error message prints when err != nil [OK]
Hint: If error returned, print error message, not result [OK]
Common Mistakes:
  • Assuming result prints even if error exists
  • Ignoring error check and printing zero
  • Expecting runtime panic instead of error
4. Identify the error in this Go code snippet:
package main
import (
    "fmt"
    "os"
)
func readFile() error {
    file, err := os.Open("data.txt")
    if err != nil {
        return err
    }
    defer file.Close()
    // read file contents
    return nil
}

func main() {
    err := readFile()
    if err != nil {
        fmt.Println("File read successfully")
    }
}
medium
A. The error check in main should be err == nil, not err != nil
B. The defer statement is misplaced and should be before error check
C. The function readFile should return a string, not error
D. os.Open does not return an error

Solution

  1. Step 1: Examine the error handling in main

    The main function calls readFile() and prints "File read successfully" if err != nil.
  2. Step 2: Identify the logic error

    err != nil means an error occurred, so printing success here is incorrect. Success should be printed only if err == nil (no error).
  3. Final Answer:

    The error check in main should be err == nil, not err != nil -> Option A
  4. Quick Check:

    Print success only if err == nil [OK]
Hint: Print success only when err == nil, not err != nil [OK]
Common Mistakes:
  • Confusing err == nil and err != nil conditions
  • Moving defer before error check incorrectly
  • Expecting os.Open to never return error
5. You want to write a Go function that tries to open a file and returns a custom error message if it fails. Which code snippet correctly wraps the original error with a custom message using Go's standard library?
hard
A. file, err := os.Open("config.json") if err != nil { panic(err) } return file.Close()
B. file, err := os.Open("config.json") if err != nil { return errors.New("failed to open config") } return file.Close()
C. file, err := os.Open("config.json") if err != nil { return fmt.Errorf("failed to open config: %w", err) } return file.Close()
D. file, err := os.Open("config.json") if err != nil { return err.Error() } return file.Close()

Solution

  1. Step 1: Understand error wrapping in Go

    Go 1.13+ supports wrapping errors with fmt.Errorf and %w verb to keep original error context.
  2. Step 2: Check each option for correct wrapping

    file, err := os.Open("config.json") if err != nil { return fmt.Errorf("failed to open config: %w", err) } return file.Close() uses fmt.Errorf with %w to wrap original error, preserving it. file, err := os.Open("config.json") if err != nil { return errors.New("failed to open config") } return file.Close() creates new error losing original error. file, err := os.Open("config.json") if err != nil { panic(err) } return file.Close() panics instead of returning error. file, err := os.Open("config.json") if err != nil { return err.Error() } return file.Close() returns string instead of error type.
  3. Final Answer:

    file, err := os.Open("config.json") if err != nil { return fmt.Errorf("failed to open config: %w", err) } return file.Close() -> Option C
  4. Quick Check:

    Use fmt.Errorf with %w to wrap errors [OK]
Hint: Use fmt.Errorf("%w") to wrap errors with context [OK]
Common Mistakes:
  • Replacing original error instead of wrapping
  • Using panic instead of returning error
  • Returning error message string instead of error type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard