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.youkuaiyun.com/fengfengdiandia/article/details/80058805
本文介绍了如何在 Go 语言中使用 `panic` 和 `recover` 进行错误处理。示例代码展示了在 panic 发生时如何打印堆栈信息,并通过 `recover` 捕获异常。此外,还提供了使用 `runtime.Caller` 获取调用堆栈的详细信息,以及通过 `debug.Stack()` 打印堆栈的两种方法。
3万+

被折叠的 条评论
为什么被折叠?



