Go by Example: Errors

Here’s an example in Go that demonstrates how to handle errors:

package main

import (
	"errors"
	"fmt"
)

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

func main() {
	result, err := divide(10, 5)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Println("result:", result)
	}
	
	result, err = divide(10, 0)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Println("result:", result)
	}
}

In this example, we define a function divide that takes two int values as input and returns the result of the division. The function also returns an error value to indicate whether or not an error occurred during the division.

We use the errors.New function to create a new error value when the denominator is zero. If the denominator is not zero, the function returns nil as the error value.

In the main function, we call the divide function twice and check the error value returned by the function. If an error occurred, we print the error message to the screen. If no error occurred, we print the result of the division to the screen.

The output of this program will be:

result: 2
error: cannot divide by zero

As you can see, the program correctly handles the error when dividing by zero and prints the error message to the screen.

Here’s an example in Go that demonstrates how to create and use custom error types:

package main

import (
	"fmt"
)

type DivisionByZeroError struct {
	message string
}

func (e DivisionByZeroError) Error() string {
	return e.message
}

func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, DivisionByZeroError{"cannot divide by zero"}
	}
	return a / b, nil
}

func main() {
	result, err := divide(10, 5)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Println("result:", result)
	}
	
	result, err = divide(10, 0)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Println("result:", result)
	}
}

In this example, we define a custom error type DivisionByZeroError that implements the Error method. The Error method returns a string that represents the error message.

In the divide function, we use the custom error type to indicate when a division by zero error occurs.

In the main function, we use the custom error type in the same way as in the previous example. The only difference is that we now use the custom error type instead of the built-in error type.

The output of this program will be the same as in the previous example:

result: 2
error: cannot divide by zero

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *