go language exceptions panic and restore recover usage instances

  • 2020-05-27 05:48:59
  • OfStack

This article illustrates the use of go language exceptions panic and restore recover. Share with you for your reference. The specific analysis is as follows:

You can throw an panic exception in go, then catch the exception in defer via recover and handle it normally
This is important in the structure of one main process with multiple go process logic, which can cause the entire process to fail if recover is not used to catch panic exceptions

package main
import "fmt"
func main() {
defer func() {     // You have to declare it first defer , otherwise it cannot be captured panic abnormal
if err := recover(); err != nil {
fmt.Println(err)    // Here, err In fact, is panic The incoming content, 55
func f() {

I hope this article has been helpful to your programming of Go language.

Related articles: