panic
# panic
panic 会停止当前函数的正常流程,执行已注册的 defer,并沿调用栈向上传播。它适合表示程序内部不变量被破坏,而不是普通输入错误。
func mustPort(port int) int {
if port < 1 || port > 65535 {
panic("port outside valid range")
}
return port
}
1
2
3
4
5
6
2
3
4
5
6
可恢复的配置错误、网络错误和用户输入错误都应返回 error。库代码随意 panic 会把恢复责任推给调用者;MustXxx 风格函数只有在初始化失败无法继续时才合理,并应在命名上明确行为。