golang panic打印
(1.)示例代码
package main
import (
"fmt"
"os"
"runtime"
)
func main() {
defer func() {
if e := recover(); e != nil {
panic.PrintStack()
os.Exit(1)
}
}()
zero := 0
x := 3 / zero
fmt.Println("x=", x)
}
// PrintStack 打印堆栈信息
func PrintStack() {
var buf [4096]byte
n := runtime.Stack(buf[:], false)
fmt.Printf("==> %s\n", string(buf[:n]))
}
示例二:
package main
import (
"fmt"
"runtime"
)
func stupidCode() {
n := 0
fmt.Println(1/ n)
}
func main() {
defer func() {
if err := recover(); err != nil {
for i := 0; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fmt.Println(pc, file, line)
}
}
}()
stupidCode()
}
package main
import (
"fmt"
"runtime"
)
func stupidCode() {
n := 0
fmt.Println(1/ n)
}
func main() {
defer func() {
if err := recover(); err != nil {
for i := 0; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fmt.Println(pc, file, line)
}
}
}()
stupidCode()
}
示例三:
import (
"fmt"
"runtime/debug"
)
func test3() {
// 可以通过 debug.PrintStack() 直接打印,也可以通过 debug.Stack() 方法获取堆栈然后自己打印
fmt.Printf("%s", debug.Stack())
debug.PrintStack()
}
参考链接
https://blog.csdn.net/fengfengdiandia/article/details/80058805