post image :date_long | 1 min Read

Go panic() recover() and defer()

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")
}
``
author image

Jan Toth

I have been in DevOps related jobs for past 6 years dealing mainly with Kubernetes in AWS and on-premise as well. I spent quite a lot …

comments powered by Disqus