All about defer, panic and recover

func printStrings() {
1. fmt.Println("Beginning of the function")
2. defer fmt.Println("Deferred Call")
3. fmt.Println("End of the function")
4.}
OUTPUT:
Beginning of the function
End of the function
Deferred Call
func sampleStrings() {
str := "begin"
defer fmt.Println(str)
str = "end"
}
OUTPUT:
begin
func abc() {
defer fmt.Println("a")
defer fmt.Println("b")
defer fmt.Println("c")
}
OUTPUT:
c
b
a
func test() {
1. fmt.Println("start")
2. defer fmt.Println("deferred")
3. panic("something bad happened")
4. fmt.Println("end")
}
OUTPUT
start
deferred
panic: something bad happened

goroutine 1 [running]:
main.main()
/tmp/sandbox214463821/prog.go:4 +0xfe
func main() {
fmt.Println("begin")
panicker()
fmt.Println("end")
}
func panicker() {
fmt.Println("about to panic")
// Anonymous Function begins
defer func() {
if err := recover(); err != nil {
log.Println("Err: ", err)
}
}() //Anonymous function call(defined and called at the same time)
panic("something bad happened")
fmt.Println("done panicking")
}
OUTPUT:
begin
about to panic
2009/11/10 23:00:00 Err: something bad happened
end

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

[Java][Linked List][LeetCode] Rotate List #61

Day 8 of my Developer Journey: Spawn Manager

| Engineering News-Record

Make the world better with Smart Cloud! — Ericsson & Junction 2018

Keep an Eye on These 5 Software Development Trends in 2022

Keep an Eye on These 5 Software Development Trends in 2022

How to make own timer trigger using docker container + azure function + ACI

Lane Detection using Hough Transformation

7 Intriguing No-Code Tools Worth Trying

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aman Jain

Aman Jain

Software Engineer

More from Medium

How did I discover APIs?

Coding Guide Spotlight: Rego Style Guide

Model-driven Engineering

Car Wash Pattern: Parallelizing Non-Thread Safe and/or CPU-intensive Processes with Future Based…