0
0
Goprogramming~5 mins

Returning errors in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the common way to return errors in Go functions?
In Go, functions often return an error as the last return value. If there is no error, the error value is nil.
Click to reveal answer
beginner
How do you check if a function returned an error in Go?
You compare the returned error value to nil. If it is not nil, an error occurred and should be handled.
Click to reveal answer
intermediate
What does the following Go code return?
func divide(a, b int) (int, error) {
  if b == 0 {
    return 0, fmt.Errorf("cannot divide by zero")
  }
  return a / b, nil
}
This function returns the result of a divided by b and nil error if b is not zero. If b is zero, it returns 0 and an error with the message "cannot divide by zero".
Click to reveal answer
intermediate
Why is it useful to return errors instead of panicking in Go?
Returning errors allows the caller to decide how to handle the problem, making the program more robust and easier to maintain.
Click to reveal answer
beginner
What package is commonly used to create error values in Go?
The fmt package is commonly used with fmt.Errorf to create formatted error messages.
Click to reveal answer
In Go, what does a function usually return to indicate an error?
AAn error value as the last return value
BA boolean true or false
CA panic message
DA string describing the error
How do you check if a Go function returned an error?
ACheck if error is true
BCheck if error equals zero
CCheck if error is nil
DCheck if error is empty string
What does fmt.Errorf do in Go?
ACreates a formatted error value
BPrints an error message
CStops the program
DReturns a boolean
What should you do if a Go function returns a non-nil error?
AReturn nil
BIgnore it
CAlways panic
DHandle the error appropriately
Which of these is a correct function signature for returning an error in Go?
Afunc example() error int
Bfunc example() (int, error)
Cfunc example() error
Dfunc example() int error
Explain how to return and check errors in a Go function.
Think about how Go functions signal problems and how callers respond.
You got /3 concepts.
    Describe why returning errors is preferred over panicking in Go programs.
    Consider the difference between stopping a program and letting it recover.
    You got /3 concepts.