Golang error catch Panic and Recover

Golang error capture Panic and Recover, I caught you, Error

Golang easy to learn


1. What are Golang errors?

For Go language (Golang) errors are returned by the way to force the caller to handle the error, either you ignore it with _ or you handle it. For this design method, we usually need to write a lot of if err != nil judgments. We can do it by method.
There are many such codes. Although most of the errors in the project are nil, that is, there is no error, but when it is not nil, it means that an error has occurred.
In Go language, use multi-value return to return an error. In Go, a panic exception can be thrown, and then the exception is caught by recover in the defer, and then processed normally.

2. Error checking

1. Method

When there is an error, we use the method to determine whether to panic:

func Panic(err error) {
    
    

	if err != nil {
    
    
		panic(err)
	}

}

2. Misjudgment

The code is as follows (example):

If no method

for _, c := range []string{
    
    "1", "2"} {
    
    

		atoi, err := strconv.Atoi(c)
		if err != nil {
    
    
			return
		}
		fmt.Println(atoi)
	}

If the method

But at this time panic also requires us to do extra processing to capture the error

	for _, c := range []string{
    
    "1", "2"} {
    
    

		atoi, err := strconv.Atoi(c)
		Panic(err)
		fmt.Println(atoi)
	}

3. Error capture

1. Method

When there is an error, we judge whether the panic is generated by recovering:

func RecoverError() {
    
    

	if err := recover(); err != nil {
    
    
		//输出panic信息
		fmt.Println(err)

		//输出堆栈信息
		fmt.Println(string(debug.Stack()))
	}
}

2. Use of defer

Since our capture must be after the error is generated, we must ensure that the capture method is called after the error handling method, that is, the final call of the method is controlled by defer:

func main() {
    
    
	// 当使用defer 时,将会在程序内方法结算后,
	// 依照后进先出的方法执行defer内方法
	// 此时就能保证 捕获程序一定能捕获到错误
	defer RecoverError()
	for _, c := range []string{
    
    "1", "2"} {
    
    

		atoi, err := strconv.Atoi(c)
		Panic(err)

		fmt.Println(atoi)
	}

}

Summarize

Through the above, it is easy to get familiar with the different error handling forms of Golang and other languages. Since developers of other languages ​​often mix exceptions with control structures, it can easily clutter the code. It's also very easy for developers to abuse exceptions, throwing an exception for even a small mistake. This is not allowed in Golang, and Go language does not support the traditional try...catch...finally exception, which is handled by the new defer panic recover.

Hope this blog will be useful to you. I am the King of Light, and I speak for myself.

Guess you like

Origin blog.csdn.net/moer0/article/details/123593492