Post

Go panic() recover() and defer()

How to use panic, recover, and defer in Go for error handling, including recovering from panics in deferred functions.

This program covers Go’s panic, recover, and defer mechanisms. A panic immediately stops the current function and begins unwinding the stack. A defer statement schedules a function to run just before the surrounding function returns, even during a panic. The recover function, when called inside a deferred function, captures the panic value and allows the program to continue running instead of crashing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main

import (
	"fmt"
	// "strconv"
	// "math"
	// "reflect"
	"net/http"
	"log"

)

func simplePanic()  {
	a, b := 1, 0
	ans := a/b
	fmt.Printf("ans: %v\n", ans)
}

func usePanic()  {
	fmt.Printf("start\n")
	panic("something bad happened")
	fmt.Printf("end\n")
}



func panicInWebAPP()  {
	http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request)  {
		w.Write([]byte("Hello Go!"))
	})

	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		panic(err.Error())
	}

}

func deferIsExecutedBeforePanic()  {
	fmt.Printf("start\n")
	defer fmt.Printf("this was defered\n")
	panic("something bad happened")
	fmt.Printf("end\n")
}


func xdeferIsExecutedBeforePanic()  {
	fmt.Printf("start\n")
	defer func()  {
		if err := recover(); err != nil {
			log.Printf("Something bad happended error: %v\n", err)
			// if the error is so bad
			// simply use:
			// panic("I cannot handle it anymore :)")
		}

	}()
	panic("Panic something bad happened\n")
	fmt.Printf("end\n")
}


func main() {
	// simplePanic()
	// usePanic()
	// panicInWebAPP()
	xdeferIsExecutedBeforePanic()
	fmt.Printf("end\n")
}
This post is licensed under CC BY 4.0 by the author.