So wie try/catch-Block in Ausnahme in Sprachen wie Java , C# usw. verwendet werden, um Ausnahmen in ähnlicher Weise in der Go-Sprache abzufangen, wird die Wiederherstellungsfunktion verwendet, um Panik zu behandeln. Es ist eine eingebaute Funktion, die unter dem eingebauten Paket der Go-Sprache definiert ist. Der Hauptzweck dieser Funktion besteht darin, die Kontrolle über eine in Panik geratene Goroutine wiederzuerlangen. Oder mit anderen Worten, es behandelt das panische Verhalten der Goroutine .

Syntax:

func recover() interface{}

Wichtige Punkte:

  • Die Wiederherstellungsfunktion wird immer innerhalb der verzögerten Funktion aufgerufen, nicht in der normalen Funktion. Wenn Sie die Wiederherstellungsfunktion innerhalb der normalen Funktion oder außerhalb der verzögerten Funktion aufrufen, stoppt die Wiederherstellungsfunktion die Paniksequenz nicht, wie in Beispiel 1 gezeigt. Daher wird die Wiederherstellungsfunktion immer innerhalb der verzögerten Funktion aufgerufen, da die verzögerte Funktion ihre Ausführung nicht stoppt Wenn das Programm in Panik gerät, stoppt die Wiederherstellungsfunktion die Paniksequenz, indem sie einfach die normale Ausführung der Goroutine wiederherstellt und den an den Aufruf von Panic übergebenen Fehlerwert abruft, wie in Beispiel 2 gezeigt.
  • Die Wiederherstellungsfunktion funktioniert nur, wenn Sie dieselbe Goroutine aufrufen, in der Panik auftritt. Wenn Sie es in einer anderen Goroutine aufrufen, funktioniert es nicht wie in Beispiel 3 gezeigt.
  • Wenn Sie den Stack-Trace finden möchten, verwenden Sie die PrintStack-Funktion, die unter Debug-Paket definiert ist.

Beispiel 1:

// Go program which illustrates
// the concept of recover
package main
  
import "fmt"
  
// This function is created to handle
// the panic occurs in entry function
// but it does not handle the panic 
// occurred in the entry function
// because it called in the normal
// function
func handlepanic() {
  
    if a := recover(); a != nil {
        fmt.Println("RECOVER", a)
    }
}
  
// Function
func entry(lang *string, aname *string) {
  
    // Normal function
    handlepanic()
  
    // When the value of lang
    // is nil it will panic
    if lang == nil {
        panic("Error: Language cannot be nil")
    }
      
    // When the value of aname
    // is nil it will panic
    if aname == nil {
        panic("Error: Author name cannot be nil")
    }
      
    fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)
    fmt.Printf("Return successfully from the entry function")
}
  
// Main function
func main() {
  
    A_lang := "GO Language"
    entry(&A_lang, nil)
    fmt.Printf("Return successfully from the main function")
}

Ausgabe:

panic: Error: Author name cannot be nil

goroutine 1 [running]:
main.entry(0x41a788, 0x0)
    /tmp/sandbox777592252/prog.go:35 +0x180
main.main()
    /tmp/sandbox777592252/prog.go:46 +0x40

Beispiel 2:

// Go program which illustrates
// the concept of recover
package main
  
import (
    "fmt"
)
  
// This function handles the panic
// occur in entry function
// with the help of the recover function
func handlepanic() {
  
    if a := recover(); a != nil {
      
        fmt.Println("RECOVER", a)
    }
}
  
// Function
func entry(lang *string, aname *string) {
  
    // Deferred function
    defer handlepanic()
  
    // When the value of lang
    // is nil it will panic
    if lang == nil {
      
        panic("Error: Language cannot be nil")
    }
      
    // When the value of aname
    // is nil it will panic
    if aname == nil {
        panic("Error: Author name cannot be nil")
    }
    fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)
    fmt.Printf("Return successfully from the entry function")
}
  
// Main function
func main() {
  
    A_lang := "GO Language"
    entry(&A_lang, nil)
    fmt.Printf("Return successfully from the main function")
}

Ausgabe:

RECOVER Error: Author name cannot be nil
Return successfully from the main function

Beispiel 3:

// Go program which illustrates
// recover in a goroutine
package main
  
import (
    "fmt"
    "time"
)
  
// For recovery
func handlepanic() {
    if a := recover(); a != nil {
        fmt.Println("RECOVER", a)
    }
}
  
/* Here, this panic is not 
   handled by the recover 
   function because of the 
   recover function is not 
   called in the same 
   goroutine in which the 
   panic occurs */
  
// Function 1
func myfun1() {
  
    defer handlepanic()
    fmt.Println("Welcome to Function 1")
    go myfun2()
    time.Sleep(10 * time.Second)
}
  
// Function 2
func myfun2() {
  
    fmt.Println("Welcome to Function 2")
    panic("Panicked!!")
}
  
// Main function
func main() {
  
    myfun1()
    fmt.Println("Return successfully from the main function")
}

Ausgabe:

Welcome to Function 1
Welcome to Function 2
panic: Panicked!!

goroutine 6 [running]:
main.myfun2()
    /tmp/sandbox157568972/prog.go:31 +0xa0
created by main.myfun1
    /tmp/sandbox157568972/prog.go:24 +0xc0