Adding a new example: recover

With thanks to @LaryBattle for the discussion in #46 and
@kilaka for the discussion in #344.

Fixes #46
Closes #344
This commit is contained in:
Eli Bendersky
2021-09-01 08:51:00 -07:00
parent 5525fed5ae
commit 91c8ceec2c
8 changed files with 247 additions and 3 deletions

View File

@@ -0,0 +1,41 @@
// Go makes it possible to _recover_ from a panic, by
// using the `recover` built-in function. A `recover` can
// stop a `panic` from aborting the program and let it
// continue with execution instead.
// An example of where this can be useful: a server
// wouldn't want to crash if one of the client connections
// exhibits a critical error. Instead, the server would
// want to close that connection and continue serving
// other clients. In fact, this is what Go's `net/http`
// does by default for HTTP servers.
package main
import "fmt"
// This function panics.
func mayPanic() {
panic("a problem")
}
func main() {
// `recover` must be called within a deferred function.
// When the enclosing function panics, the defer will
// activate and a `recover` call within it will catch
// the panic.
defer func() {
if r := recover(); r != nil {
// The return value of `recover` is the error raised in
// the call to `panic`.
fmt.Println("Recovered. Error:\n", r)
}
}()
mayPanic()
// This code will not run, because `mayPanic` panics.
// The execution of `main` stops at the point of the
// panic and resumes in the deferred closure.
fmt.Println("After mayPanic()")
}

View File

@@ -0,0 +1,2 @@
053ecbddb4f4a1d881aa40086de99da4e78b9990
Sk-SVdofEIZ

View File

@@ -0,0 +1,2 @@
Recovered. Error:
a problem