C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Defer: In divideByZero we specify a nested "defer" method. In this func we assign err to the result of recover().
And: If err is not nil, we take an action that can repair the program's state and keep it from terminating.
Tip: In this program, if we remove the divide by zero error, the value of "dog" will be printed. And the "defer" func will never be called.
Golang program that uses recover, defer func
package main
import "fmt"
func divideByZero() {
// Use this deferred function to handle errors.
defer func() {
if err := recover(); err != nil {
fmt.Println("HERE")
fmt.Println(err)
fmt.Println(0)
}
}()
// Cause an error.
// ... Go will run the defer func above.
cat := 0
dog := 10 / cat
fmt.Println(dog)
}
func main() {
// Create a divide by zero error and handle it.
divideByZero()
}
Output
HERE
runtime error: integer divide by zero
0
Tip: When panic is called, the stack is unwound. And each method is tested for a defer method.
Recover: The recover() method returns panic's error. In this program, the WRONG message is provided.
Golang program that uses panic, defer and recover
package main
import "fmt"
func explode() {
// Cause a panic.
panic("WRONG")
}
func main() {
// Handle errors in defer func with recover.
defer func() {
if err := recover(); err != nil {
// Handle our error.
fmt.Println("FIX")
fmt.Println("ERR", err)
}
}()
// This causes an error.
explode()
}
Output
FIX
ERR WRONG
Result: The "type string is not an expression" error occurs. Use the correct identifier "name" for a working program.
Golang program that causes type string error
package main
import "fmt"
func mistake(name string) {
// We put the wrong variable name.
// ... Use "name" not string.
fmt.Println(string)
}
func main() {
mistake("cat")
}
Output
# command-line-arguments
C:\programs\file.go:11: type string is not an expression