GO language exception handling mechanisms panic and recover analysis

  • 2020-05-09 18:43:50
  • OfStack

This paper analyzes the GO language exception handling mechanisms panic and recover by example. Share with you for your reference. The details are as follows:

Golang has two built-in functions, panic() and recover(), to report and catch program errors that occur at run time. Unlike error, panic-recover 1 is used inside functions. Be careful not to abuse panic-recover, which can cause performance problems. I only use it for unknown input and unreliable requests.

The error handling process of golang: when an exception occurs during the execution of a function or panic() is encountered, the normal statement will terminate immediately, then the defer statement will be executed, the exception information will be reported, and goroutine will be exited. If the recover() function is used in defer, the error message is caught, causing the error message to terminate the report.

Example:

package main
import (
 "log"
 "strconv"
) // Catch program exceptions due to unknown input
func catch(nums ...int) int {
 defer func() {
  if r := recover(); r != nil {
   log.Println("[E]", r)
  }
 }()  return nums[1] * nums[2] * nums[3] //index out of range
} // Take the initiative to throw panic , is not recommended and may cause performance problems
func toFloat64(num string) (float64, error) {
 defer func() {
  if r := recover(); r != nil {
   log.Println("[W]", r)
  }
 }()  if num == "" {
  panic("param is null") // Take the initiative to throw panic
 }  return strconv.ParseFloat(num, 10)
} func main() {
 catch(2, 8)
 toFloat64("")
}

The output is as follows:

2014/11/01 22:54:23 [E] runtime error: index out of range
2014/11/01 22:54:23 [W] param is null

I hope this article has helped you with your GO programming.


Related articles: