capypad
0 day streak
go / beginner
Snippet

Creating and Handling Errors

Go handles errors explicitly via return values, not exceptions. Functions return an error as the last return value. nil means no error occurred. The errors.New() function creates a simple error message. Always check errors before using other return values.

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
23
24
25
26
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, 2)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Result: %d\n", result)
_, err = divide(5, 0)
if err != nil {
fmt.Println("Caught error:", err)
}
}
Breakdown
1
func divide(a, b int) (int, error)
Error is returned as last value; callers must check it
2
errors.New("division by zero")
Creates a new error with the given message string
3
return a / b, nil
nil returned when operation succeeds; signals no error to caller
4
if err != nil { ... }
Standard pattern: check if error is not nil, then handle it