go-101/ Defer, panic and recover

Defer statement defers the execution of a function until the surrounding function returns. Multiple defers are pushed into stack and executes in Last In First Out (LIFO) order. Defer generally used to cleanup resources like file, database connection etc. Lets see the example below:

Basic understanding of defer

As we know defer push statements into stack in a LIFO order, check it below:

It’ll print 4,3,2,1,0 . Go here to learn more about defer .Defer statements are executed after the function return, generally useful to catch errors.

Panic is similar to throwing exception like other language. Generally when a panic is called then the normal execution flow is stops immediately, but the deffered functions are executed normally. It is a built-in function in golang.

See the result in palyground. Read more about panic here.

Recover is another built-in function in go. It helps to regain the normal flow of execution after a panic. Generally it used with defer statement to recover panic in goroutine. Lets use all the three statements we learned in the series to see the recover example.

Panic and recover

Run the code in go play ground. Read more about recover here.

Note: I’ll try to update all of my articles in this series. To get update follow me on twitter or medium. One more thing, if you find any mistake or misleading in these articles please knock me or write a comment. Thank you

If you like my writing please follow me Saddam H.

Software Engineer, Pathao Inc | Open Source Enthusiast | Love to write elegant code | Gopher by passion | https://thedevsaddam.github.io

Software Engineer, Pathao Inc | Open Source Enthusiast | Love to write elegant code | Gopher by passion | https://thedevsaddam.github.io