packagemainimport ( "fmt")funcfullName(firstName *string, lastName *string) { 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")}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*/
packagemainimport ( "fmt")funcfullName(firstName *string, lastName *string) { defer fmt.Println("deferred call in fullName")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")}funcmain() { defer fmt.Println("deferred call in main") firstName :="Elon"fullName(&firstName, nil) fmt.Println("returned normally from main")}/*deferred call in fullName deferred call in main panic: runtime error: last name cannot be nilgoroutine 1 [running]: main.fullName(0x1042bf90, 0x0) /tmp/sandbox060731990/main.go:13 +0x280main.main() /tmp/sandbox060731990/main.go:22 +0xc0*/
packagemainimport ( "fmt")funcrecoverName() { if r :=recover(); r!=nil { fmt.Println("recovered from ", r) }}funcfullName(firstName *string, lastName *string) { deferrecoverName()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")}funcmain() { 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 nilnormally returned from maindefered call from main routine
packagemainimport ( "fmt""time")funcrecovery() { if r :=recover(); r !=nil { fmt.Println("recovered:", r) }}funca() { deferrecovery() fmt.Println("Inside A")gob() time.Sleep(1* time.Second)}funcb() { fmt.Println("Inside B")panic("oh! B panicked")}funcmain() { a() fmt.Println("normally returned from main")}
typeErrorinterface {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 methodRuntimeError()}
import"fmt"funcoutOfBound() {deferrecovery() a := []int{1, 2, 0} fmt.Println(a, a[1]/a[2]) fmt.Println("normally returned from outOfBound")}funcrecovery() {if r :=recover(); r !=nil { fmt.Println("recover successfully") }}funcmain() {outOfBound() fmt.Println("normally returned from main")}