Go Program to Create Custom Errors

Introduction

In Go, you can create custom errors to provide more context or specific information about an error condition. Custom errors can be created using the errors.New function or by implementing the error interface. This guide will demonstrate how to create and use custom errors in Go.

Problem Statement

Create a Go program that:

  • Implements a function that may return a custom error.
  • Defines and uses custom error messages.
  • Displays appropriate messages based on whether an error occurred or not.

Example:

  • Operation: Checking if a number is positive.
  • Output:
    The number is positive.
    

    or

    Error: the number is not positive.
    

Solution Steps

  1. Import the Necessary Packages: Use import "fmt" and import "errors" for creating and handling errors.
  2. Create a Custom Error: Define a custom error using errors.New.
  3. Write a Function that Returns a Custom Error: Implement a function that checks a condition and returns the custom error if the condition is not met.
  4. Handle the Custom Error in the Main Function: Check if the error is not nil and handle it appropriately.
  5. Display the Result: Use fmt.Println to display whether the operation succeeded or if the custom error occurred.

Go Program

package main

import (
    "errors"
    "fmt"
)

// Step 2: Create a custom error
var ErrNotPositive = errors.New("the number is not positive")

// Step 3: Implement a function that returns a custom error
func checkPositive(number int) error {
    if number <= 0 {
        return ErrNotPositive // Return the custom error if the number is not positive
    }
    return nil // Return nil if the number is positive
}

/**
 * Go Program to Create Custom Errors
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 4: Prompt the user to enter a number
    var number int
    fmt.Print("Enter a number: ")
    fmt.Scanln(&number)

    // Step 5: Call the function and handle the custom error
    err := checkPositive(number)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("The number is positive.")
    }
}

Explanation

Step 2: Create a Custom Error

  • The ErrNotPositive variable is defined using errors.New to create a custom error with the message "the number is not positive".
    • This custom error can be returned by functions when a specific error condition occurs, providing more context about what went wrong.

Step 3: Implement a Function that Returns a Custom Error

  • The checkPositive function checks whether the provided number is positive.
    • If the number is not positive (i.e., it is zero or negative), the function returns the custom error ErrNotPositive.
    • If the number is positive, the function returns nil, indicating no error.

Step 4: Handle the Custom Error in the Main Function

  • The main function calls checkPositive and checks if the returned error is not nil.
    • If err is not nil, it indicates that the number was not positive, and the program prints the custom error message.
    • If err is nil, it means the number was positive, and the program prints a success message.

Step 5: Display the Result

  • The program uses fmt.Println to print either the success message or the custom error message.

Output Example

Example 1:

If the number is positive:

Enter a number: 5
The number is positive.

Example 2:

If the number is zero or negative:

Enter a number: -3
Error: the number is not positive.

Example 3:

If the number is zero:

Enter a number: 0
Error: the number is not positive.

Conclusion

This Go program demonstrates how to create and use custom errors using the errors.New function. It covers basic concepts such as defining custom errors, returning them from functions, and handling them appropriately. This example is useful for beginners learning Go programming and understanding how to provide more informative error messages.

Leave a Comment

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

Scroll to Top