Junior — Middle
How is exception and error management implemented in your application?
sobes.tech AI
Answer from AI
Error handling in Go differs from many other languages because there are no exceptions in the traditional sense. Instead, functions typically return an error value (error) as a second result.
Main approaches:
-
Checking the error after a function call:
result, err := someFunction() if err != nil { // handle error log.Println("Error:", err) return err } // continue working with result -
Creating custom error types using
errors.Neworfmt.Errorffor more informative messages. -
Panic (
panic) and recover (recover) are used rarely, mainly for critical errors that should not occur during normal operation. -
Logging errors and returning them up the stack for centralized handling.
Example of error handling:
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, in Go, errors are handled explicitly, which enhances code readability and reliability.