capypad
0 day streak
go / beginner
Snippet

Error Handling with Multiple Return Values

Go uses multiple return values for error handling, a core design pattern. Functions return both a value and an error. The error is nil on success, otherwise it contains the error message. The `if err != nil` pattern is used throughout Go code.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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("Error:", err)
return
}
fmt.Println("Result:", result)
}
Breakdown
1
(int, error)
Function signature declares two return values: int and error
2
errors.New("...")
Creates a new error with the given message string
3
return a / b, nil
Returns result as first value, nil error as second for success case