Error Handling
Examples in
Go
A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.
package main
import "os"
func main() {
panic("a problem")
_, err := os.Create("/tmp/file")
if err != nil {
panic(err)
}
}
You can return a value after recovering a function by using named result parameters.
package main
import "fmt"
func main() {
fmt.Println("Returned:", MyFunc())
}
func MyFunc() (ret string) {
defer func() {
if r := recover(); r != nil {
ret = fmt.Sprintf("was panic, recovered value: %v", r)
}
}()
panic("test")
return "Normal Return Value"
}