← Back to Go Course | Chapter 9: Error Handling | Lesson 1 of 6

error Interface क्या है

Go में एक error बस एक छोटा box है जो यह बताने वाला एक message रख सकता है कि क्या गलत हुआ -- और fail हो सकने वाला हर function आपको जांचने के लिए एक वापस देता है।
Syntax
go
type error interface {
    Error() string
}

err := errors.New("message")
if err != nil {
    // handle error
}

The error Interface Itself

Go का built-in error type बस एक single method वाला एक interface है, Error() string। इस method को implement करने वाली कोई भी type एक error के रूप में उपयोग की जा सकती है, जो पूरी language में error handling को साधारण और uniform रखता है।

उदाहरण: The error Interface Itself

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define a struct type named MyError
type MyError struct {
	Msg string
}

// Define the method Error on type MyError
func (e *MyError) Error() string {
	// Send e.Msg back to the caller
	return e.Msg
}

// main is where the program starts running
func main() {
	var err error = &MyError{Msg: "something went wrong"}
	// Print the values followed by a newline
	fmt.Println(err)
}

Creating Errors with errors.New

एक error produce करने का सबसे सरल तरीका errors.New("message") है, जो वह static text रखने वाली एक basic error value return करता है -- सीधी failure conditions के लिए आदर्श।

उदाहरण: Creating Errors with errors.New

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"errors"
	"fmt"
)

// Define the function checkAge
func checkAge(age int) error {
	// Check whether age < 0
	if age < 0 {
		return errors.New("age cannot be negative")
	}
	// Send nil back to the caller
	return nil
}

// main is where the program starts running
func main() {
	// Check whether err := checkAge(-5); err != nil
	if err := checkAge(-5); err != nil {
		// Print the values followed by a newline
		fmt.Println("error:", err)
	}
}

Creating Errors with fmt.Errorf

fmt.Errorf Printf-style formatting उपयोग करके एक error बनाता है, आपको एक अलग Sprintf call के बिना error message में सीधे dynamic values embed करने देते हुए।

Note: जब message को कोई dynamic data चाहिए तो errors.New से fmt.Errorf को आमतौर पर प्राथमिकता दी जाती है।

उदाहरण: Creating Errors with fmt.Errorf

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function checkStock
func checkStock(item string, qty int) error {
	// Check whether qty <= 0
	if qty <= 0 {
		return fmt.Errorf("item %q is out of stock", item)
	}
	// Send nil back to the caller
	return nil
}

// main is where the program starts running
func main() {
	// Run this block only if the condition is true
	if err := checkStock("widget", 0); err != nil {
		// Print the values followed by a newline
		fmt.Println(err)
	}
}

The if err != nil Idiom

standard Go pattern fail हो सकने वाली किसी call के ठीक बाद error result जांचना है, और आगे बढ़ने से पहले इसे handle या propagate करना -- यह failure paths को explicit और चुपचाप skip होने से असंभव बनाता है।

उदाहरण: The if err != nil Idiom

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"strconv"
)

// main is where the program starts running
func main() {
	// Short declaration: create n, err and infer the type
	n, err := strconv.Atoi("not-a-number")
	// Handle the error if one occurred
	if err != nil {
		// Print the values followed by a newline
		fmt.Println("failed to parse:", err)
		return
	}
	// Print the values followed by a newline
	fmt.Println("parsed:", n)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी returned error को पूरी तरह नज़रअंदाज़ करना (_ उपयोग करके या बस इसे न जांचकर) बजाय इसे handle या propagate करने के।
  2. dynamically बनाए errors को == से compare करना, bजाय wrapped errors के लिए errors.Is उपयोग करने के।
  3. यह मान लेना कि errors.New(fmt.Sprintf(...)) idiomatic है बजाय सीधे fmt.Errorf उपयोग करने के, जो wrapping के लिए %w support करता है।
चैप्टर सारांश
  • error एक built-in interface है जिसे एक method चाहिए: Error() string।
  • Fail हो सकने वाले functions conventionally अपना result plus आखिरी return value के रूप में एक error return करते हैं।
  • errors.New और fmt.Errorf एक साधारण error बनाने के दो आम तरीके हैं।
  • किसी call के ठीक बाद 'if err != nil' जांचना standard Go error-handling idiom है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.