Handle error in golang

(3 minutes for reading)

Different from Java, Python, javascript or .NET, in Golang, you can not try and catch error. You need to handle error by your code. Go’s approach makes it easy to see which functions return errors and to handle them using the same language constructs employed for any other, non-error tasks.

By convention, errors are the last return value and have type error, a built-in interface.

errors.New constructs a basic error value with the given error message

nil value in the error position indicates that there was no error.

import "errors"

func checkArrayMode2(arr []int) (bool, error) {
    for _, value := range arr {
    if value % 2 != 0 {
        return false, errors.New("Fail")
    }
}
    return true, nil
}

func main() {
    arr := []int {1,2,3,4,5}
    result, err := checkArrayMode2(arr)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}

Because Golang not support try catch, you should alway handle your function by error. But error can only contain one message, so it so hard to show what you say on error. I will show you a way to custom error in article about advance Golang then

View on github

PreNext