Error management is a fundamental aspect of building robust and observable applications, and it should be as important as any other part of a codebase. In Go, error management doesn’t rely on the traditional try/catch mechanism as most programming languages do. Instead, errors are returned as normal return values.
It’s pretty common for Go newcomers to be somewhat confused about error handling. In Go, errors are usually managed by functions or methods that return an error type as the last parameter. But some developers may find this approach surprising and be tempted to reproduce exception handling in languages such as Java or Python using panic and recover. So, let’s refresh our minds about the concept of panic and discuss when it’s considered appropriate or not to panic.
func main() { fmt.Println("a") panic("foo") fmt.Println("b") }
a panic: foo goroutine 1 [running]: main.main() main.go:7 +0xb3