panic()
andrecover()
are two important functions used in Go language to handle errors.panic()
Functions are used to abort the program and raise panic, andrecover()
Functions are used to capture panic and restore program execution.
What are panic and recover?
panic
-
panic()
Functions are used to abort the program and raise panic. -
panic()
The function can receive a parameter that will be used as the reason for panic. - When panic occurs, the program stops execution and starts looking for the most recent recovery call.
- If the recovery call cannot be found, the program will print the reason for panic and exit.
recover
-
recover()
Functions are used to capture panic and restore program execution. -
recover()
The function can receive a parameter that will store the reason for the panic. - If recovery is called when panic occurs, the program will continue to execute and the reason for panic will be stored in the first parameter of recovery.
func main() { defer func() { err := recover() if err != nil { ("panic:", err) } }() panic("hello, panic!") }
The spread of panic
The panic function will be propagated upward to the goroutine that calls it. If the panic function is not captured, it will continue to propagate upward until it encountersdefer
Called in the statementrecover()
Function, or program exit.
Things to note
Cross coroutine failure
panic
andrecover
Cannot be used across coroutines. This means that panics that occur in a coroutine can only pass in the same coroutinerecover
Capture. If panic occurs in one coroutine and is called in another coroutinerecover
,Sorecover
Panic will not be captured. Refer to the following code:
func main() { defer println("in main") go func() { defer println("in goroutine") panic("") }() (1 * ) }
Failed crash recovery
If panic occurs in a defer function, the statements following the defer function will not be executed. This means using it in the defer functionrecover
To capture panic is invalid.
func main(){ defer ("main....") defer func() { err := recover() if err != nil { ("panic:", err) } }() panic("hello, panic!") }
Nesting crash
Nesting crash refers to calling in a goroutinepanic()
Function, then indefer
Called again in the statementpanic()
Function. in this case,panic()
The function will propagate from the inside out until the program crashes. Nesting crashes may cause the program to be unavailable and should be avoided.
func multiplePanic() { defer ("in defer") defer func() { defer func() { panic("panic 3") }() panic("panic 2") }() panic("panic 1") }
This is the end of this article about the usage examples of Go language panic and recover. For more relevant Go language panic and recover content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!