Context:
In the provided code:
<code class="go">func sub(){ defer func (){ panic(2) }() panic(1) } func main(){ defer func(){ x:=recover() println(x.(int)); }() sub() }</code>
It appears that the first panic (panic(1)) is "overwritten" by the second panic (panic(2)).
Is it Acceptable?
In Golang, panicking from a deferred function does not constitute a distinct or exceptional condition. It simply indicates that the panic sequence will persist.
As demonstrated in the example code, it is permissible to call a Golang function that might panic within a defer function. Even when a panic is already occurring, it is acceptable to panic within a defer function.
Mechanism:
According to the Go specification:
"If D returns normally, without starting a new panic, the panicking sequence stops."
In the example, the deferred function (D) returns without triggering a new panic. Therefore, the panicking sequence initiated by panic(1) is halted.
Additional Considerations:
The above is the detailed content of Can You Panic Within a Defer Function During an Existing Panic in Golang?. For more information, please follow other related articles on the PHP Chinese website!