RecoverPanic让panic正常跑

RecoverPanic让panic正常跑

目标

在我们写程序时候,想让程序错误继续运行,一般我们会容错error。但是对于数组越界,我们还想让go函数跑的话,不影响主题函数,看以下代码

代码实现

用recover()

package _func

import (
	"fmt"
	"time"
)

func Client()  {
	for {
		go myPainc()
		go normal()
		time.Sleep(time.Second)
	}
}

func myPainc() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("出了错:", err)
			return
		}
	}()

	arr := make([]string, 0)
	arr = append(arr, "1")
	fmt.Println(arr[8]) // 看,这是重大错误
}

func normal()  {
	fmt.Println("正常运算")
}

## 输出
正常运算
出了错: runtime error: index out of range [8] with length 1
正常运算
出了错: runtime error: index out of range [8] with length 1
正常运算
出了错: runtime error: index out of range [8] with length 1
出了错: runtime error: index out of range [8] with length 1
正常运算
出了错: runtime error: index out of range [8] with length 1
正常运算

Process finished with exit code 2

recover

The recover built-in function allows a program to manage behavior of a panicking goroutine. Executing a call to recover inside a deferred function (but not any function called by it) stops the panicking sequence by restoring normal execution and retrieves the error value passed to the call of panic. If recover is called outside the deferred function it will not stop a panicking sequence. In this case, or when the goroutine is not panicking, or if the argument supplied to panic was nil, recover returns nil. Thus the return value from recover reports whether the goroutine is panicking.

恢复内置功能允许程序管理紧急恐慌例程的行为。在延迟函数(但不是由它调用的任何函数)中执行恢复调用将通过恢复正常执行来停止恐慌序列,并检索传递给panic调用的错误值。如果在延迟函数之外调用了restore,它将不会停止恐慌序列。在这种情况下,或者当goroutine没有惊慌时,或者如果提供给panic的参数为nil,则restore返回nil。因此,来自recovery的返回值将报告goroutine是否感到恐慌。

原文地址:https://www.cnblogs.com/maomaomaoge/p/14343109.html