Recovering from panic

Follow the latest of Whizdumb’s journey here.

We all must panic when Voldemort returns, however we must be quick to recover from panic also.

Whenever we expect a situation where panic can occur we must be ready to recover from it and must defer the recovery to the end of the function call so that all possible panic situations in the function are taken care of.

To help us recover we have a recover() function which acts like a finally in Java, where we can handle an exception and it will always be executed.

Let us see how we can use it.

package main
import "fmt"
func main() {
   defer func() {
        str := recover()
        fmt.Println(str)
        fmt.Println("No Worries Harry! We got you (re)covered!!")
      }()  
    fmt.Println("Everything is good")
    fmt.Println("Panic is going to occur now!!")
    panic("Lord Voldemort has returned!!")
    fmt.Println("Panic has occured!")
}
}

In the above main method, the first line is a deferred function, which will be executed just before the method exits (due to any reason).

When we run the code, panic occurs (When lord Voldemort returns), but deferred function gets executed now.

The recover() method in the function allows us to recover and it returns the string which was passed when panic occured.

Here is the output that we finally receive

Everything is good
Panic is going to occur now!!
Lord Voldemort has returned!!
No Worries Harry! We got you (re)covered!!

Notice that recover() makes sense in a deferred function. Had the function not been deferred we would not have been able to recover from panic situation.

What happens if we encounter a panic situation in deferred function which was supposed to handle panic?

Well, In theory we could multiple deferred functions each trying to cover the ass of the other. Like in the following code

package main
import "fmt"
func main() {
   defer func(){
     str:= recover()
     fmt.Println(str)
     fmt.Println("Harry takes matters in his own hand!")
    }()
   defer func() {
        str := recover()
        fmt.Println(str)
        fmt.Println("No Worries Harry! We got you (re)covered!!")
        panic("Dumbledore is dead....")
      }()  
    fmt.Println("Everything is good")
    fmt.Println("Panic is going to occur now!!")
    panic("Lord Voldemort has returned!!")
    fmt.Println("Panic has occured!")
}

We need to decide how many deferred functions we can have like that and must take a call to have a fail proof defer, sooner the better!

Later!

~~ Whizdumb ~~