Golang : How To Use Panic and Recover
In this tutorial we will understand how panic function works and how to "interrupt and recover" from the panic.
First, let's examine Panic function
package main
import "fmt"
func startPanic() {
defer func() {
fmt.Println("This will APPEAR")
}()
panic("noooo!")
}
func main() {
fmt.Println("Starting to panic...")
startPanic()
fmt.Println("This WILL NOT APPEAR ")
}
Output :
Starting to panic..
This will APPEAR
panic: noooo!
as you can see from the output. The string "This WILL NOT APPEAR" .... well, will not appear because the Panic function was invoked before the fmt.Println("This WILL NOT APPEAR ").
There are times when we need to recover from the panic and move on with life. This code below will demonstrate just that :
package main
import "fmt"
func startPanic() {
defer func() {
if error := recover(); error != nil {
fmt.Println("Recovering....", error)
}
}()
panic("noooo!")
}
func main() {
fmt.Println("Starting to panic...")
startPanic()
fmt.Println("This will APPEAR because of Recover")
}
Output :
Starting to panic...
Recovering.... noooo!
This will APPEAR because of Recover
What happen here is that we manage to catch the error with the recover() function.
if error := recover(); error != nil {
fmt.Println("Recovering....", error)
}
You can further enhance the error handling depending on your needs. Learn more at http://blog.golang.org/error-handling-and-go
Hope this tutorial will be helpful for those learning Go.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.1k Golang : How do I get the local IP (non-loopback) address ?
+5.6k Golang : Derive cryptographic key from passwords with Argon2
+7.1k Golang : Auto-generate reply email with text/template package
+8.9k Golang : Get current, epoch time and display by year, month and day
+11.8k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+9.8k Golang : Natural string sorting example
+8.2k Random number generation with crypto/rand in Go
+6.3k Golang : Getting Echo framework StartAutoTLS to work
+4.2k Golang : Pad file extension automagically
+5k Facebook : How to force facebook to scrape latest URL link data?
+10.1k CodeIgniter : How to check if a session exist in PHP?
+16.1k Golang : Find smallest number in array