Sobes.tech
Junior — Middle

What error handling methods are you familiar with?

sobes.tech AI

Answer from AI

In Go, error handling is usually built on returning an error value from a function and checking it. The main methods:

  1. Returning an error as a value — the function returns an error as the last return parameter. The calling code checks if err != nil.
func readFile(name string) ([]byte, error) {
    data, err := os.ReadFile(name)
    if err != nil {
        return nil, err
    }
    return data, nil
}

func main() {
    data, err := readFile("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
}
  1. Panic and recover — for critical errors that should not happen under normal circumstances. panic stops the program, recover allows handling the panic.

  2. The errors package and error wrapping — for creating and enriching errors with additional information.

  3. Using custom error types — for more precise handling of different error types.

In Go, exceptions are not used as in other languages; errors are handled explicitly.

What error handling methods are you familiar with… - sobes.tech