Golang恐慌崩溃预防 [英] Golang panic crash prevention

查看:659
本文介绍了Golang恐慌崩溃预防的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang中,没有恢复的恐慌会导致进程崩溃,所以我最终在每个函数的开始处放置了以下代码片段:

 推迟func(){
如果err:= recover(); err!= nil {
fmt.Println(err)
}
}()

只是为了防止我的程序崩溃。现在我想知道,这真的是要走的路吗?因为我认为在任何地方放置相同的代码看起来有点奇怪。



在我看来,使用Java的方式将异常冒泡到调用函数,直到主要功能是控制异常/恐慌的更好方法。我明白这是Go的设计,但是立即崩溃的过程就像Go所做的那样有什么优势? 如果你确切地知道原因,只有从恐慌中恢复过来。一个Go程序在下列两种情况下会出现恐慌:


  • 程序逻辑错误(例如零指针解引用或超出边界数组或切片访问)

  • 从您的代码或代码中使用您的代码引发的故意恐慌(使用 panic(...))调用



在第一种情况下,崩溃是合适的,因为这意味着您的程序进入了错误状态,并且不应该继续执行。在第二种情况下,如果您期望的话,您应该只从恐慌中恢复过来。解释这种情况的最好方式就是说它非常罕见,如果你看到它,你就会知道这种情况。我几乎肯定,无论你在写什么代码,你都不需要从恐慌中恢复过来。


In Golang a panic without a recover will crash the process, so I end up putting the following code snippet at the beginning of every function:

defer func() {
    if err := recover(); err != nil {
        fmt.Println(err)
    }
}()

just in order to prevent my program from crashing. Now I'm wondering, is it really the way to go? Because I think it looks a little bit strange to put the same code everywhere.

It seems to me, the Java way, bubbling the exceptions up to the calling function, until the main function is a better way to control the exceptions/panics. I understand it's by Go's design, but what is the advantage of immediately crashing the process just like what Go does?

解决方案

You should only recover from a panic if you know exactly why. A Go program will panic under essentially two circumstances:

  • A program logic error (such as a nil pointer dereference or out-of-bounds array or slice access)
  • An intentional panic (called using panic(...)) from either your code or code that your code calls

In the first case, a crash is appropriate because it means that your program has entered a bad state and shouldn't keep executing. In the second case, you should only recover from the panic if you expect it. The best way to explain this is simply to say that it's extremely rare, and you'll know that case if you see it. I'm almost positive that whatever code you're writing, you don't need to recover from panics.

这篇关于Golang恐慌崩溃预防的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆