Home > Article > Backend Development > Can You Panic Inside a Defer Function During an Existing Panic in Go?
In the given Go code snippet, a panic occurs in the sub() function. A deferred function inside sub() then panics again, with a different value. The question is, is it permissible to panic inside a defer function, particularly when the program is already panicking?
Yes, it is acceptable to panic within a defer function, even during an existing panic. Panicking from a deferred function does not initiate a unique or extraordinary state; it simply prolongs the panic sequence.
The provided code example demonstrates that panicking from a defer function is harmless and even allows for recovery using recover() at a higher level.
According to the Go specification on Handling Panics:
"If a function on the same goroutine panics, the deferred functions will run in the same order they were deferred, with the outermost deferred function (the one called last) running first. If any deferred function calls recover and a panic occurred anywhere in the goroutine, the value passed to recover will be the value passed to the initial call to panic."
While it is permissible to panic inside a defer function, it is important to note that:
The following example illustrates this behavior:
<code class="go">func main() { defer func() { fmt.Println("Checkpoint 1"); panic(1) }() defer func() { fmt.Println("Checkpoint 2"); panic(2) }() panic(999) }</code>
Output:
Checkpoint 2 Checkpoint 1 panic: 999 panic: 2 panic: 1
All deferred functions execute, and the values passed to all panic() calls are included in the final panic sequence.
Panicking inside a defer function, even during an existing panic, is acceptable in Go. However, it is important to be aware of the order and consequences of deferred function execution, and to use recover() appropriately to handle panics.
The above is the detailed content of Can You Panic Inside a Defer Function During an Existing Panic in Go?. For more information, please follow other related articles on the PHP Chinese website!