recover function to catch exceptions

package main

import (
	//"fmt"
	"time"
)

func test () {
	var m map[string]int
	m["abcd"] = 1234
}

func main () {
	for i := 0; i < 100; i++ {
		go test()
	}

	time.Sleep(10 * time.Second)
}

  Do not use recover (), it will directly affect the panic behind the process

  

2. Use the recover ()

  

//recover来捕获异常
package main

import (
	"fmt"
	"time"
)

func test () {
	//使用recover来捕获异常
	defer func () {
		if err := recover(); err != nil {
			fmt.Println("panic", err)
		}
	}()

	var m map[string]int
	m["abcd"] = 1234
}

func main () {
	for i := 0; i < 100; i++ {
		go test()
	}

	time.Sleep(10 * time.Second)
}

  

  Process will not panic

 

Guess you like

Origin www.cnblogs.com/zhangxiaoj/p/11267294.html