In Go,panic
andrecover
is a keyword used to handle runtime exceptions. Here is a summary and example of their usage:
1. The role of panic
-
Trigger condition: When the program encounters serious errors that cannot be recovered (such as unpredictable logic errors, missing dependencies, etc.),
panic
Will terminate the execution of the current function and trigger upward layer by layerdefer
, if not finallyrecover
Capture, the program will crash. -
Applicable scenarios:
- Key resources are missing in the initialization phase (such as configuration files, database connections).
- An unrecoverable exception (such as failure of assertion) appears in the code logic.
2. Basic usage
package main import \"fmt\" func main() { defer func() { if r := recover(); r != nil { (\"Recovered from panic:\", r) } }() (\"Start\") panic(\"something bad happened\") // Trigger panic (\"End\") // Will not execute}
Output:
Start
Recovered from panic: something bad happened
3. Recover usage rules
- Must be with
defer
Combined:recover
Only indefer
Effective in the function. - Valid only on the current goroutine: Panics for other goroutines cannot be captured.
func mayPanic() { panic(\"a problem occurred\") } func main() { defer func() { if r := recover(); r != nil { (\"Recovered. Error:\", r) } }() mayPanic() // Trigger panic (\"After mayPanic()\") // Will not execute}
4. Error handling suggestions
- Priority return
error
: General errors should be returned by multiple values (e.g.error
Type) Processing. - Use with caution
panic
: Use only in severe errors or unrecoverable scenarios (such as program startup failure). - In a key position
recover
: For example, in the goroutine's ingress or in the HTTP request processor, preventing the program from crashing.
Web server example:
func handleRequest() { defer func() { if err := recover(); err != nil { (\"Request failed:\", err) } }() // Process request logic (possibly trigger panic)}
5. Common error scenarios
- Uncaught panic: If not
defer
Called inrecover
, the program will crash. - Cross goroutine panic: Each goroutine needs to handle its own panic independently.
Summarize
-
panic
: Used to terminate program execution and pass error information. -
recover
:existdefer
Capture panic in the process and restore the program flow. - Best practice: Use error return values first, only if necessary
panic
andrecover
。
By using these two keywords reasonably, the program's robustness can be improved and crashes caused by unhandled exceptions can be avoided.
This is the end of this article about the usage of golang panic function. For more related golang panic function content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!