panic — an unrecoverable runtime error that stops normal execution. error — an expected failure that can be handled gracefully.
panic behavior:
recover().recover() is found, the program crashes.1func riskyOperation() {2 // This will crash the program3 panic("something went terribly wrong")4}56// Built-in functions that panic:7var s []int8_ = s[0] // index out of range panic9var m map[string]int10_ = m["key"] // nil map access panic11var p *int12_ = *p // nil pointer dereference panic
error behavior:
1func divide(a, b int) (int, error) {2 if b == 0 {3 return 0, errors.New("division by zero")4 }5 return a / b, nil6}78// Caller handles the error9result, err := divide(10, 0)10if err != nil {11 log.Printf("Error: %v", err)12 return // graceful handling13}
When to use panic:
init() functions (configuration must be valid).When to use error:
Common mistakes:
result, _ := divide(10, 0)).log.Fatal which calls os.Exit(1) — deferred functions won't run.