Sobes.tech
Junior — Middle

What types of exceptions or errors can be handled in the Go language?

sobes.tech AI

Answer from AI

In the Go language, there is no traditional exception system like in some other languages. Instead, errors are handled using return values of type error.

Main ways to handle errors in Go:

  • Returning an error from a function: the function returns a value and an error, which must be checked.
  • Panic and recover: used for handling critical errors that usually lead to program termination but can be caught.

Example of error handling:

func readFile(filename string) ([]byte, error) {
    data, err := os.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return data, nil
}

func main() {
    data, err := readFile("file.txt")
    if err != nil {
        fmt.Println("Error reading file:", err)
        return
    }
    fmt.Println(string(data))
}

Thus, in Go, errors returned by functions are handled, not exceptions in the traditional sense.