Use panic only for unrecoverable errors like invalid invariants or fatal system failures; return an error for expected, recoverable conditions.
// Recoverable: return error
func readFile(path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err // Caller can handle missing file
}
return data, nil
}
// Unrecoverable: panic
func divide(a, b int) int {
if b == 0 {
panic("division by zero is not allowed") // Logic error
}
return a / b
}