1024programmer Java How to make the function return data during gopanic?

How to make the function return data during gopanic?

Now there is a question: if a function is executed normally, it will return 0, and if it panics, it will return 1. How to do this?

 package main
 import "fmt"
 func test() int {
  defer func() {
  if err := recover(); err != nil {
   return 1
  }
  }()
  var p*int
  *p = 0
  return 0
 }
 func main() {
  fmt.Println("ret is", test())
  for {}
 }

This obviously doesn’t work, because return 1 is for the anonymous function, not the test function.

Let’s look at an ingenious method:

 package main
 import "fmt"
 func test() (a int) {
  defer func() {
  if err := recover(); err != nil {
   a = 1
  }
  }()
  var p*int
  *p = 0
  return 0
 }
 func main() {
  fmt.Println("ret is", test())
  for {}
 }

OK.

Not much to say.

Summary

The above is the entire content of this article. I hope that the content of this article has certain reference and learning value for everyone’s study or work. Thank you for your support. If you want to know more related content, please check out the relevant links below

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/784271

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索