panic — immediate runtime failure. error — expected failure returned as value.
Panic:
recover().1// Panic for invariant violations2func MustParse(s string) Config {3 cfg, err := Parse(s)4 if err != nil {5 panic("invalid config: " + err.Error())6 }7 return cfg8}910// Recover at boundary11func safeWorker() {12 defer func() {13 if r := recover(); r != nil {14 log.Printf("panic: %v", r)15 }16 }()17 // ... work18}
Error:
1func readData(path string) ([]byte, error) {2 data, err := os.ReadFile(path)3 if err != nil {4 return nil, fmt.Errorf("reading %s: %w", path, err)5 }6 return data, nil7}
When to use panic:
init() failures.When to use error:
Common mistakes:
errors.Is/errors.As.log.Fatal instead of error.