Return and check errors
Return and check errors
An error is a value implementing the built-in error interface, whose method is Error() string. Functions commonly return a result and an error. A nil error means success under the function contract. Check the error before using a result that is only valid on success.
package main
import ( "errors" "fmt")
func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("zero divisor") } return a / b, nil}func main() { n, err := divide(12, 3) if err != nil { fmt.Println(err) return } fmt.Println(n) _, err = divide(12, 0) fmt.Println(err)}The function explicitly rejects a zero divisor. Its error branch returns zero as a placeholder, not a successful quotient. The caller handles the error before reading the result. Integer division truncates toward zero.
Expected output:
4zero divisorPropagate a parsing failure
package main
import ( "errors" "fmt" "strconv")
func positive(s string) (int, error) { n, err := strconv.Atoi(s) if err != nil { return 0, err } if n <= 0 { return 0, errors.New("must be positive") } return n, nil}func main() { for _, s := range []string{"4", "-2", "abc"} { n, err := positive(s) if err != nil { fmt.Println("rejected") continue } fmt.Println(n) }}The early return avoids using the failed parse. Atoi converts decimal text into int and reports invalid or out-of-range input. Some APIs deliberately return partial results with errors; read their contracts instead of assuming every non-nil error invalidates all results.
Expected output:
4rejectedrejectedTry it locally
Write half(n int)(int,error) accepting only even numbers. Print the result for 8 and the error message "odd number" for 3.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 01: Return and check errors
Check the lesson objective before moving on.
What should you check before using a success-only result?
Can an API return useful partial data with an error?