Errors
Go has no exceptions. Functions return an error as the last value and callers check it with if err != nil. Create errors with errors.New or fmt.Errorf.
Example
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("divide by zero")
}
return a / b, nil
}
func main() {
if _, err := divide(1, 0); err != nil {
fmt.Println("error:", err)
}
v, _ := divide(9, 3)
fmt.Println(v)
}Result
error: divide by zero 3
Exercise
Check for a failure.
if err nil {}
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.