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
+45k Golang : Marshal and unmarshal json.RawMessage struct example
+10.7k Golang : Simple file scaning and remove virus example
+8.9k Golang : Sort and reverse sort a slice of floats
+8.2k Golang : Intercept and compare HTTP response code example
+10.7k Golang : GTK Input dialog box examples
+15.7k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+9.7k Golang : Simple File Server
+7.4k Golang : Find relative luminance or color brightness
+9.2k Golang : Get escape characters \u form from unicode characters
+6k Golang : Get expvar(export variables) to work with multiplexer
+5.8k Golang : Calculate diameter, circumference, area, sphere surface and volume
+9.2k Golang : Find and replace data in all files recursively