Panic vs Error
Besides returning an error, Go has a second mechanism: panic. When a panic happens, the function stops immediately, Go "unwinds" the call stack, and, if nothing catches it, the program crashes with a message and a stack trace.
func ambilLevel(level int) string {
if level < 1 {
panic("level tidak boleh kurang dari 1")
}
return fmt.Sprintf("Level %d", level)
}
Panics are also triggered by Go itself at run time, for example integer division by zero or a failed type assertion without comma ok.
When to use which?
| Situation | Use |
|---|---|
| Failures that are expected to happen: bad user input, a missing file, insufficient balance, a dropped network | error |
| Conditions that should be impossible, a sign of a bug in the program | panic |
| A failure during initialization that makes it impossible for the program to run | panic (or log.Fatal) |
Rule of thumb: almost always use error. A good library doesn't crash the programs that use it just because of bad input.
recover (a quick look)
A panic can be caught with recover inside a deferred function. defer schedules a function to run right before the surrounding function finishes, including when it panics.
func aman() {
defer func() {
if r := recover(); r != nil {
fmt.Println("pulih dari panic:", r)
}
}()
panic("ada yang salah")
}
recover is rarely used in everyday code; usually only at the program's "boundary", such as a web server that doesn't want the whole process to die because of one bad request.
Try it yourself
The editor holds an example comparing the two approaches. Press Run, then try:
- Change
bagiAman(10, 0)tobagiAman(10, 2). - Remove the
defer ... recoverblock injalankanDenganPengamanand see what happens when the program runs.