Bird
Raised Fist0
Goprogramming~20 mins

Returning errors in Go - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Go Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Go code with error handling?

Consider the following Go code that tries to open a file and returns an error if it fails. What will be printed when the file does not exist?

Go
package main

import (
	"fmt"
	"os"
)

func openFile(filename string) error {
	_, err := os.Open(filename)
	return err
}

func main() {
	err := openFile("nonexistent.txt")
	if err != nil {
		fmt.Println("Error occurred:", err)
	} else {
		fmt.Println("File opened successfully")
	}
}
AFile opened successfully
BError occurred: open nonexistent.txt: no such file or directory
CError occurred: <nil>
DCompilation error: missing return statement
Attempts:
2 left
💡 Hint

Think about what happens when os.Open tries to open a file that does not exist.

❓ Predict Output
intermediate
2:00remaining
What error does this Go function return?

Look at this Go function that returns an error. What will be the output when calling checkValue(5)?

Go
package main

import (
	"errors"
	"fmt"
)

func checkValue(x int) error {
	if x < 10 {
		return errors.New("value too small")
	}
	return nil
}

func main() {
	err := checkValue(5)
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println("Value is fine")
	}
}
ACompilation error: undefined errors package
BValue is fine
Cvalue too small
Dnil
Attempts:
2 left
💡 Hint

Check the condition inside checkValue and what error is returned.

🔧 Debug
advanced
2:00remaining
Which option causes a compile-time error due to wrong error return?

Identify which code snippet will cause a compile-time error because it returns a wrong type instead of an error.

Afunc doSomething() error { return "error string" }
Bfunc doSomething() error { return nil }
Cfunc doSomething() error { return fmt.Errorf("fail") }
Dfunc doSomething() error { return errors.New("fail") }
Attempts:
2 left
💡 Hint

Remember that the function must return a value of type error.

❓ Predict Output
advanced
2:00remaining
What is the output of this Go code using wrapped errors?

Consider this Go code that wraps an error. What will be printed?

Go
package main

import (
	"errors"
	"fmt"
)

func inner() error {
	return errors.New("inner error")
}

func outer() error {
	return fmt.Errorf("outer error: %w", inner())
}

func main() {
	err := outer()
	fmt.Println(err.Error())
}
Aouter error
Binner error
CCompilation error: unknown verb %w
Douter error: inner error
Attempts:
2 left
💡 Hint

Look at how %w is used in fmt.Errorf.

❓ Predict Output
expert
3:00remaining
What is the output of this Go code using custom error type and error interface?

Analyze this Go code with a custom error type implementing the error interface. What will be printed?

Go
package main

import (
	"fmt"
)

type MyError struct {
	Code int
	Msg  string
}

func (e *MyError) Error() string {
	return fmt.Sprintf("Error %d: %s", e.Code, e.Msg)
}

func doTask(fail bool) error {
	if fail {
		return &MyError{Code: 404, Msg: "Not Found"}
	}
	return nil
}

func main() {
	err := doTask(true)
	if err != nil {
		switch e := err.(type) {
		case *MyError:
			fmt.Println("Custom error detected:", e.Error())
		default:
			fmt.Println("Other error:", err.Error())
		}
	} else {
		fmt.Println("Task succeeded")
	}
}
ACustom error detected: Error 404: Not Found
BOther error: Error 404: Not Found
CTask succeeded
DCompilation error: cannot use &MyError literal as error
Attempts:
2 left
💡 Hint

Check how the type assertion works with the custom error type.

Practice

(1/5)
1.

What does a Go function return when there is no error?

easy
A. It returns nil as the error value.
B. It returns 0 as the error value.
C. It returns "no error" as the error value.
D. It returns an empty string "" as the error value.

Solution

  1. Step 1: Understand Go error convention

    In Go, functions return an error type to indicate problems. If no problem occurs, the error is nil.
  2. Step 2: Identify the correct no-error return value

    The standard way to show no error is to return nil, not zero, empty string, or text.
  3. Final Answer:

    It returns nil as the error value. -> Option A
  4. Quick Check:

    No error means error = nil [OK]
Hint: No error always returns nil, never zero or empty string [OK]
Common Mistakes:
  • Returning 0 instead of nil for no error
  • Returning empty string instead of nil
  • Returning a string message instead of nil
2.

Which of the following is the correct way to declare a Go function that returns an int and an error?

func example() ???
easy
A. func example() (int, error)
B. func example() int, error
C. func example() int error
D. func example() (int error)

Solution

  1. Step 1: Recall Go function return syntax

    Go functions return multiple values by listing types in parentheses separated by commas.
  2. Step 2: Match correct syntax

    The correct syntax for returning an int and error is (int, error). Other options miss commas or parentheses.
  3. Final Answer:

    func example() (int, error) -> Option A
  4. Quick Check:

    Multiple returns use parentheses and commas [OK]
Hint: Use parentheses and commas for multiple return types [OK]
Common Mistakes:
  • Omitting parentheses for multiple returns
  • Missing comma between return types
  • Writing return types without parentheses
3.

What will be the output of this Go program?

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. runtime error
B. division by zero
C. 10
D. 0

Solution

  1. Step 1: Analyze divide function behavior

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

    Main calls divide(10, 0), gets error != nil, so prints the error message.
  3. Final Answer:

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

    Error returned prints message [OK]
Hint: If error is not nil, print error message [OK]
Common Mistakes:
  • Printing result even when error is not nil
  • Expecting 0 as output instead of error message
  • Assuming runtime panic on division by zero
4.

Identify the error in this Go function that returns an error:

func readFile(name string) (string, error) {
  data := ""
  file, err := os.Open(name)
  if err != nil {
    return data, err
  }
  defer file.Close()
  // read file content
  return data, nil
}
medium
A. Function should return only error, not string.
B. Return statement should return only data.
C. Defer statement should be before error check.
D. Missing import of os package.

Solution

  1. Step 1: Check for required imports

    The function uses os.Open but does not import os package, causing a compile error.
  2. Step 2: Verify other code parts

    Return types and defer placement are correct; only missing import is the problem.
  3. Final Answer:

    Missing import of os package. -> Option D
  4. Quick Check:

    Using os.Open requires importing os [OK]
Hint: Check imports when using standard library functions [OK]
Common Mistakes:
  • Forgetting to import packages used
  • Placing defer before error check
  • Returning wrong number of values
5.

You want to write a Go function parseNumber that takes a string and returns an int and an error. It should return an error if the string is empty or not a valid number. Which implementation correctly returns errors?

func parseNumber(s string) (int, error) {
  if s == "" {
    return 0, errors.New("empty input")
  }
  n, err := strconv.Atoi(s)
  if err != nil {
    return 0, err
  }
  return n, nil
}
hard
A. Returns error only for invalid number, not empty string.
B. Returns nil error even if input is empty.
C. Correctly returns errors for empty and invalid input.
D. Returns zero and nil error for all inputs.

Solution

  1. Step 1: Check empty string error handling

    The function returns error "empty input" if string is empty, which is correct.
  2. Step 2: Check invalid number error handling

    Uses strconv.Atoi to convert string; returns error if conversion fails.
  3. Step 3: Confirm success return

    If no error, returns parsed number and nil error.
  4. Final Answer:

    Correctly returns errors for empty and invalid input. -> Option C
  5. Quick Check:

    Empty and invalid inputs return errors [OK]
Hint: Return error immediately on invalid input [OK]
Common Mistakes:
  • Not checking empty string before conversion
  • Ignoring error from strconv.Atoi
  • Returning nil error on invalid input
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