How are errors typically handled in Go? What is a panic and how can it be handled?
sobes.tech AI
Answer from AI
In Go, errors are conventionally handled explicitly by returning an error value from a function and checking it at the call site. This allows controlling the flow of execution and making decisions when errors occur.
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("File read error:", err)
return
}
fmt.Println(string(data))
}
Panic is a mechanism used for handling critical errors when the program cannot continue normal execution. When panic is called, the function execution is interrupted, stack unwinding begins, deferred functions are executed, and if the panic is not recovered, the program terminates with an error.
You can recover from a panic using the recover() function, which is usually called in a deferred function:
func safeFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("something went wrong")
}
Thus, in Go, errors are handled through return values, and panic is used for critical situations that can potentially be recovered from using recover.