What is the reason for panic in golang?

(*-*)浩
Release: 2019-12-28 09:24:57
Original
4668 people have browsed it

What is the reason for panic in golang?

In go, when an exception occurs in the program, panic will occur. When a panic occurs, you need to use recover to capture. If there is no capture, the program exits.

panic is used to express exceptions, that is, errors that should not occur or unexpected errors.                                                                             (Recommended learning: go)

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 {}
}
Copy after login

Output results:

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 end
Copy after login

The above is the detailed content of What is the reason for panic in golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template