we use defer, panic and recover statements to handle errors.
We use defer to delay the execution of functions that might cause an error. The panic statement terminates the program immediately and recover is used to recover the message during panic.
Defer
Go - Functions > Deferred Functions
Go - Defer,Panic & Recover
package main
import "fmt"
func main() {
// defer the execution of Println() function
defer fmt.Println("Three")
defer fmt.Println("Four")
fmt.Println("One")
defer fmt.Println("Five")
fmt.Println("Two")
}
// Output
// One
// Two
// Five
// Four
// ThreeTip
When we use multiple defer in a program, the order of execution of the defer statements will be LIFO (Last In First Out).
Panic
package main
import "fmt"
func division(num1, num2 int) {
// if num2 is 0, program is terminated due to panic
if num2 == 0 {
panic("Cannot divide a number by zero")
} else {
result := num1 / num2
fmt.Println("Result: ", result)
}
}
func main() {
division(4, 2)
division(8, 0)
division(2, 8)
}
// Result: 2
// panic: Cannot divide a number by zerothe execution of the program is terminated.
Recover
The recover statement prevents the termination of the program and recovers the program from panic.
// recover function to handle panic
func handlePanic() {
// detect if panic occurs or not
a := recover()
if a != nil {
fmt.Println("RECOVER", a)
}
}
func division(num1, num2 int) {
// execute the handlePanic even after panic occurs
defer handlePanic()
// if num2 is 0, program is terminated due to panic
if num2 == 0 {
panic("Cannot divide a number by zero")
} else {
result := num1 / num2
fmt.Println("Result: ", result)
}
}
func main() {
division(4, 2)
division(8, 0)
division(2, 8)
}
// Outputs
// Result: 2
// RECOVER Cannot divide a number by zero
// Result: 0