Maison >développement back-end >Golang >Quelle est la raison de la panique à Golang ?

En go, lorsqu'une exception se produit dans le programme, une panique se produit. En cas de panique, vous devez utiliser la récupération pour capturer. S'il n'y a pas de capture, le programme se ferme.
panic est utilisé pour représenter des exceptions, c'est-à-dire des erreurs qui ne devraient pas se produire ou des erreurs inattendues. (apprentissage recommandé : aller
package main
import "fmt"
import "runtime/debug"
func fun() {
fmt.Println("fun begin")
defer func() {
//捕获panic
if err := recover(); err != nil {
debug.PrintStack()
//获取堆栈信息的字符串
fmt.Println("xxx", string(debug.Stack()))
}
}()
var p *int
//产生异常
*p = 0
fmt.Println("fun end")
//这里不执行
for {}
}
func main() {
fmt.Println("main begin")
fun()
//因为panic被recover捕获,所以下面继续执行
fmt.Println("main end")
for {}
}Résultat de sortie :
main begin
fun begin
goroutine 1 [running]:
runtime/debug.Stack(0xc000088060, 0xc00009a000, 0xa)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/debug/stack.go:24 +0xa7
runtime/debug.PrintStack()
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/debug/stack.go:16 +0x22
main.fun.func1()
/Users/xxx/test/a.go:10 +0x46
panic(0x10a9760, 0x115d520)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/panic.go:513 +0x1b9
main.fun()
/Users/xxx/test/a.go:16 +0x7f
main.main()
/Users/xxx/test/a.go:24 +0x66
xxx goroutine 1 [running]:
runtime/debug.Stack(0xc00007ada8, 0x10a9760, 0x115d520)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/debug/stack.go:24 +0xa7
main.fun.func1()
/Users/xxx/test/a.go:11 +0x4b
panic(0x10a9760, 0x115d520)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/panic.go:513 +0x1b9
main.fun()
/Users/xxx/test/a.go:16 +0x7f
main.main()
/Users/xxx/test/a.go:24 +0x66
main endCe qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!