Saturday 4 September 2021

Go Recover

 Recover is used to regain control of a program from panic or error-condition. It stops the terminating sequence and resumes the normal execution. It is called from the deferred function. It retrieves the error value passed through the call of panic. Normally, it returns nil which has no other effect.

Go recover() Example

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. func main() {  
  6.    fmt.Println(SaveDivide(100))  
  7.    fmt.Println(SaveDivide(1010))  
  8. }  
  9. func SaveDivide(num1, num2 intint {  
  10.    defer func() {  
  11.       fmt.Println(recover())  
  12.    }()  
  13.    quotient := num1 / num2  
  14.    return quotient  
  15. }  

Output:

runtime error: integer divide by zero
0
<nil>
1

No comments:

Post a Comment