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:
- Returning an error as a value — the function returns an
erroras the last return parameter. The calling code checksif 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))
}
-
Panic and recover — for critical errors that should not happen under normal circumstances.
panicstops the program,recoverallows handling the panic. -
The
errorspackage and error wrapping — for creating and enriching errors with additional information. -
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.