Defer and Panic in Golang

Defer

The defer statement allows you to perform a specific function at the end of a program, no matter where the reality calls this function. For example:

package main
import "fmt"
 
func main() {
    defer end()
    fmt.Println("Starting ...")
    fmt.Println("Working ...")
    fmt.Println("Still Working ...")
}
 
func end(){
    fmt.Println("The end of the Program!")
}

Here, the end function is called with a defer statement, so the function will be called at the very end of the program's execution, even though Its call is defined at the beginning of the main function. Specifically, we get the following console output:

Starting ...
Working ...
Still Working ...
The end of the Program!

If more than one function is called with a defer statement, the functions that are called first will be executed later. For example:

package main
import "fmt"
 
func main() {
    defer end()
    defer fmt.Println("Starting defer 1...")
    defer fmt.Println("Working defer 2 ...")
    fmt.Println("Still Working ...")
}
 
func end(){
    fmt.Println("The end of the Program!")
}

And we should get an output like this:

Still Working ...
Working defer 2 ...
Starting defer 1...
The end of the Program!

As we can see here, the first defer that we call here (the function end()) is the last one executed. 

Panic

The panic operator allows you to generate an error and exit the program:

package main
import "fmt"
 
func main() {
    fmt.Println(number(0, 5))
   
    fmt.Println("Welcome to panic")
}
func number(a, b int) int{
    if a == 0{ 
        panic("a equls zero!")
    }
    return a + b
}

To the panic operator, we can pass any message that will be displayed on the console. For example, in this case, in the number function, if the first parameter is 0, then A call is being made to panic("a equals zero!").

In the main function, the panic operator will be executed in the call because the first parameter of the number function is 0. And in this case, all subsequent operations, that come after this call, for example, it is a call to fmt.Println("Welcome to panic"), will not be executed. In this case, We get the following console:

panic: a equls zero!

goroutine 1 [running]:
main.number(...)
	/tmp/sandbox2981701568/prog.go:11
main.main()
	/tmp/sandbox2981701568/prog.go:5 +0x25

And at the end of the output, there will be diagnostic information about where the error occurred.