panic in golang code example
Example 1: golang panic
package main
import "fmt"
func recoveryPanic() {
if recoveryMessage := recover(); recoveryMessage != nil {
fmt.Println(recoveryMessage)
}
}
func main() {
name := "jane doe"
if name != "john doe" {
defer recoveryPanic()
panic("name is not john doe")
} else {
fmt.Println("nama saya adalah", name)
}
}
Example 2: the go blog defer panic recover
func c() (i int) {
defer func() { i++ }()
return 1
}
Example 3: the go blog defer panic recover
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
dst, err := os.Create(dstName)
if err != nil {
return
}
written, err = io.Copy(dst, src)
dst.Close()
src.Close()
return
}