AnyCompiler

Error Handling

Go mein ordinary error handling ke liye koi try/catch aur koi exceptions nahi hain. Iske bajaye, ek function jo fail ho sakta hai woh bas ek error ko ek extra value ke roop mein return karta hai, aur caller use explicitly check karta hai — error bas ek interface hai jiska ek method hai, Error() string.

package main

import (
	"errors"
	"fmt"
)

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return a / b, nil
}

func main() {
	result, err := divide(10, 2)
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Result:", result)
	}
}
Output
Result: 5

err check karna convention se optional nahi hai

if err != nil ek aise call ke turant baad jo ek error return karta hai, kisi bhi Go codebase mein sabse common patterns mein se ek hai. Koi language-level enforcement nahi hai, lekin idiomatic Go code har error ko check karta hai jo use wapas milta hai, wahin jahan woh return hoti hai.

package main

import (
	"errors"
	"fmt"
)

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return a / b, nil
}

func main() {
	result, err := divide(10, 0)
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Result:", result)
	}
}
Output
Error: cannot divide by zero

Aage: defer, panic, aur recover — Go ka narrow, jaan bujh kar-limited exception-like mechanism.

Practice exercise

Ek function safeDivide(a, b float64) (float64, error) likho jo ek error "cannot divide by zero" return kare agar b 0 ho, warna a/b aur nil. Use (10, 0) ke saath call karo, aur agar koi error ho to use print karo.