Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of Program crash caused by panic by using defer and recover in Go language

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how Go language uses defer and recover to solve the problem of panic causing program crash, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

Case: If we start a coroutine, but this coroutine has a panic, but we do not capture this coroutine, it will cause the program to crash, then you can use recover in the goroutine to capture the panic, processing, so that the main thread will not be affected.

The code is as follows:

package mainimport ( "fmt" "time")func sayHello() { for i := 0; i < 10; i++ { time.Sleep(time.Second) fmt.Println("hello world") }}func test() { //use defer + recover defer func() { //catch the panic thrown by test if err := recover();err!= nil{ fmt.Println("test error occurred",err) } }() //define a map var myMap map[int]string myMap[0] = "golang" //error}func main() { go sayHello() go test() for i := 0; i < 10; i++ { fmt.Println("main() ok=",i) time.Sleep(time.Second) }}

The execution result is as follows:

Thank you for reading this article carefully. I hope that Xiaobian will share the article "How to use defer and recover to solve the problem of panic causing program crash". This article is helpful to everyone. At the same time, I hope that everyone will support you a lot. Pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 256

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report