packagemainimport("fmt")funcfullName(firstName*string,lastName*string){iffirstName==nil{panic("runtime error: first name cannot be nil")}iflastName==nil{panic("runtime error: last name cannot be nil")}fmt.Printf("%s%s\n",*firstName,*lastName)fmt.Println("returned normally from fullName")}funcmain(){firstName:="Elon"fullName(&firstName,nil)fmt.Println("returned normally from main")}/*panic: runtime error: last name cannot be nilgoroutine 1 [running]: main.fullName(0x1040c128, 0x0) /tmp/sandbox135038844/main.go:12 +0x120main.main() /tmp/sandbox135038844/main.go:20 +0x80*/
package main
import (
"fmt"
)
func recoverName() {
if r := recover(); r!= nil {
fmt.Println("recovered from ", r)
}
}
func fullName(firstName *string, lastName *string) {
defer recoverName()
if firstName == nil {
panic("runtime error: first name cannot be nil")
}
if lastName == nil {
panic("runtime error: last name cannot be nil")
}
fmt.Printf("%s %s\n", *firstName, *lastName)
fmt.Println("returned normally from fullName")
}
func main() {
defer fmt.Println("deferred call in main")
firstName := "Elon"
fullName(&firstName, nil)
fmt.Println("returned normally from main")
}
recover from runtime error: the lastName is nil
normally returned from main
defered call from main routine
package main
import (
"fmt"
"time"
)
func recovery() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}
func a() {
defer recovery()
fmt.Println("Inside A")
go b()
time.Sleep(1 * time.Second)
}
func b() {
fmt.Println("Inside B")
panic("oh! B panicked")
}
func main() {
a()
fmt.Println("normally returned from main")
}
type Error interface {
error
// RuntimeError is a no-op function but
// servers to distinguish types that are run
// time error from ordinary errors: a type is
// run time error if it has a RuntimeError method
RuntimeError()
}
import "fmt"
func outOfBound() {
defer recovery()
a := []int{1, 2, 0}
fmt.Println(a, a[1]/a[2])
fmt.Println("normally returned from outOfBound")
}
func recovery() {
if r := recover(); r != nil {
fmt.Println("recover successfully")
}
}
func main() {
outOfBound()
fmt.Println("normally returned from main")
}
func r() {
if r := recover(); r != nil {
fmt.Println("Recovered", r)
debug.PrintStack()
}
}