英文:
What is the difference between panic and an assert?
问题
> Go语言没有提供断言。它们无疑很方便,但我们的经验是,程序员使用它们作为避免思考正确的错误处理和报告的依赖。
然而,Go语言提供了print和println函数,它们的行为类似于断言:
>panic:类似于print,打印后中止执行
>panicln:类似于println,打印后中止执行
这不就是断言吗?为什么他们声称上述内容,但又有panic函数?我可以看到这会导致相同的问题,只是在末尾添加了一个错误消息,这很容易被滥用。我有什么遗漏吗?
英文:
However it has print and println which does
>panic like print, aborts execution after printing
>panicln like println, aborts execution after printing
Isnt that the same thing as an assert? Why would they claim the above but have panic? i can see it leading to the same problems but adding an error msg to the end of it which can easily be abused. Am i missing something?
答案1
得分: 16
不,不是的。panic就像是“写入然后中止”,而assert就像是“测试,如果为假,则写入然后中止”。无论如何,它们都无法阻止你执行类似assert的语句。
英文:
No, it's not. panic is like "write then abort", while an assert is like "test and if it's false, write then abort". There's no way they can keep you from doing an assert-like statement anyways.
答案2
得分: 2
除了显而易见的,即panic
不会检查任何东西,而assert
会,在Go中,即使发生panic
,您也可以使用错误处理机制。
如果一个包认为发生了无法恢复的情况,它会发生panic
。
然而,包的用户,即调用者(父级)可能希望检查或记录panic
,然后继续发生panic
,或者捕获它以正确处理该情况(例如,重试或使用不同的包/函数)。
此外,assert-abort
不会调用析构函数或其他任何东西。然而,在Go中,即使发生panic
,您defer
的函数也会被执行,因此一切都会被清理。
因此,正如您所看到的,与assert
相比,panic
将允许执行各种清理任务。这就是您提供的引用所指的内容。
有关defer
,panic
和recover
的详细信息,请参阅官方博客文章。
英文:
Apart from the obvious, that panic
does not check anything while assert
does, in Go you can use mechanics for error handling, even when a panic occurs.
If a package thinks something occurs that can not be recovered from it panics.
However, the package-user, the caller (parent level) may either want to inspect or log a panic and then continue to panic, or catch it to properly handle the case (for example, try again or then use a different package/function).
Also, an assert-abort does not call destructors or anything. A panic in Go though will still call even the functions you defer
will be executed, so everything is cleaned up.
So, as you can see, a panic will allow for a variety of cleanup-tasks in contrast to asserts. That’s what the quote you gave was pointing to.
For good information on defer, panic and recover, see the official blog post on them.
答案3
得分: 1
首先,在C语言中,assert()
函数只在调试模式下中止执行。
英文:
For one, in C, assert()
only aborts execution when in debug mode.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论