Exercise 8: Error Handling in Go

Learn how to handle errors effectively in your Go programs.

Why Handle Errors?

Unlike other languages that use exceptions, Go uses explicit error handling via return values.

Comparison with Other Languages

  • Python: Uses `try/except`
  • Java: Uses `try/catch` with exception classes
  • C++: Uses `throw/catch`
  • Go: Returns an `error` value that must be manually checked

Instructions

  • 1️⃣ Create a file named errors.go.
  • 2️⃣ Add a function that returns an error if a condition is met.
  • 3️⃣ Use `errors.New()` and `fmt.Errorf()` to create errors.
  • 4️⃣ Always check if `err != nil`.

🚀 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)
    }
}

Code Explanation

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! ☕😊


☕ Buy me a coffee