Junior — Middle
What mechanisms and approaches are used in Golang for error handling?
sobes.tech AI
Answer from AI
In Go, error handling is based on returning an error value (of type error) from functions. Instead of exceptions, explicit error checks are used after calling a function.
Main approaches:
- Functions return two values: the result and an error
error. - The error is checked using
if err != nil. - Errors are created using
errors.Neworfmt.Errorf. - For more complex handling, the
errorspackages (e.g.,errors.Is,errors.As) can be used to check and wrap errors.
Example:
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, 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)
}
Thus, Go encourages explicit and straightforward error handling without using exceptions.