Different programming languages handle errors, exceptions and recovery in different ways. Go employs defer, panic, and recover which work closely with each other to ensure smooth execution of the program.

I will go over each function very briskly to touch the usage and reasoning behind it.

Defer

Defer keyword converts a function into a special type of function which when called, gets added to a list of saved function calls. This list of saved calls is executed when the surrounding function is returned. Here a surrounding function means the function within which defer was called.

Aim: The function gets evaluated at the time of call but executes when the surrounding function is returned.

Working: once this function gets called during the execution of program, it ensures two things:-

  1. The function and it’s argument values are evaluated at the time of call.
  2. The function is scheduled to be executed right before the surrounding function returns.

#golang #recover #panic #error-handling #defer

Defer, Panic and Recover in Golang
4.15 GEEK