Sobes.tech
Junior — Middle

How is error handling implemented in Go, similar to exception mechanisms in other languages?

sobes.tech AI

Answer from AI

In the Go language, error handling is implemented through return values rather than exceptions, as in many other languages. Functions and methods typically return two values: the result and an error. If the error is not nil, it means an error has occurred and it needs to be handled.

Example of error handling in Go:

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 does not have a try-catch construct; instead, errors are passed and checked explicitly, which promotes more explicit and controlled error management.

How is error handling implemented in Go, similar to… - sobes.tech