/* * This code uses a third party module. To use this third party module takes a bit of * work: * go get github.com/pkg/errors * then * go mod init name * go mod tidy * the first makes a local copy of the package, the second sets up a package referece * the third puts into go.mod the requirement for the package. * It seems like in most cases, this could all be done by a single preprocessor within * the compile workflow. But it is not ... Sigh * Reason -- this approach allows developer to specifiy a particular * version of an imported library. Thus, new features/bugs or changes * to old features in an imported module do not impact code * Finally to run: * go run . or go run except1.go * Note that coderunner in VSC does not understand this and will fail on running * this code. */ package main import ( "fmt" "github.com/pkg/errors" ) func main() { basicPanic(1, 3) basicPanic(-1, 1) basicPanic(1, 3) err := betterPanic(-1, 3) if err != nil { fmt.Printf("ERR %+v\n", err) } err2 := betterPanic2(-1, 3) if err2 != nil { fmt.Printf("ERR %+v\n", err2) } } func basicPanic(mn, mx int) { pp := func() { fmt.Println("Basic PP!") r := recover() if r != nil { fmt.Printf("Basic Recovered in main %+v\n", r) } } defer pp() for c := mn; c <= mx; c++ { pprinter(128, c) } } func pprinter(qq, c int) { fmt.Printf("dd %d %d\n", c, (qq / c)) } func betterPanic(mn, mx int) error { var err error qqqq := func() { var c int pp := func() { fmt.Println("Better PP!") r := recover() if r != nil { fmt.Printf("Better Recovered in main %+v\n", r) err = errors.New(fmt.Sprintf("My textt -- text from recovery --> %v", r)) } } defer pp() for c = mn; c <= mx; c++ { pprinter(128, c) } } qqqq() fmt.Printf("BETTER %v\n", err) return err } func betterPanic2(mn, mx int) (err error) { var c int pp := func() { fmt.Println(" Better 2 PP!") r := recover() if r != nil { //fmt.Printf("Recovered in main %+v\n", r) err = errors.New(fmt.Sprintf("My textt -- text from recovery --> %v", r)) } } defer pp() for c = mn; c <= mx; c++ { pprinter(128, c) } fmt.Printf("BETTER2 %v\n", err) return }