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
+6.5k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+10.7k Golang : Fix go.exe is not compatible with the version of Windows you're running
+20.3k Golang : Secure(TLS) connection between server and client
+13.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+19.9k Golang : Count number of digits from given integer value
+18.3k Golang : Send email with attachment
+9.4k Golang : Validate IPv6 example
+46k Golang : Marshal and unmarshal json.RawMessage struct example
+16.1k Golang : Convert slice to array
+12.1k Golang : Validate email address
+10.3k Golang : Create matrix with Gonum Matrix package example
+23.6k Golang : Use regular expression to validate domain name