Learn how to handle errors effectively in your Go programs.
Unlike other languages that use exceptions, Go uses explicit error handling via return values.
errors.go
.🚀 Once ready, run your program!
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero is not allowed")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
1️⃣ errors.New()
: Creates a simple error.
2️⃣ return 0, error
: Returns an error instead of crashing the program.
3️⃣ if err != nil
: Checks if an error occurred.
✅ If everything is correct, you should see:
Error: division by zero is not allowed
📚 Learn more about error handling in Go:
Read the official documentation ← Previous Exercise🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊