Go के महत्वपूर्ण विषय

Go defer, panic and recover

Run cleanup code when a function returns, and turn a panic back into an ordinary error.

  • मध्यम
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • defer
  • Deferred calls run in reverse
  • recover
readConfig()
  1. 1open fileruns first
  2. 2defer closescheduled
  3. 3read settingsruns second
  4. 4close fileruns on return

Cleanup that always runs

defer schedules a call to run when the surrounding function returns, which makes it the usual way to close files and release locks. A panic stops the normal flow, and recover, called in a deferred function, catches it.

close file prints after read settings because the deferred call runs when readConfig returns. Dividing by zero panics; the deferred function recovers and stores an error in the named result err. The three deferred calls in main run last, in reverse order.

मुख्य बातें

  1. A deferred call runs when the function returns.
  2. Several defers run last in, first out.
  3. recover catches a panic inside a deferred function.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import "fmt"

func readConfig() {
	fmt.Println("open file")
	defer fmt.Println("close file") // runs when the function returns
	fmt.Println("read settings")
}

func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

func main() {
	readConfig()

	for i := 1; i <= 3; i++ {
		defer fmt.Println("deferred", i) // last in, first out
	}

	fmt.Println(safeDivide(10, 2))
	fmt.Println(safeDivide(1, 0))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
open file
read settings
close file
5 <nil>
0 recovered: runtime error: integer divide by zero
deferred 3
deferred 2
deferred 1

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Closures and Function Values →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज