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
- Import the Necessary Packages: Use
import "fmt"andimport "errors"for creating and handling errors. - Create a Custom Error: Define a custom error using
errors.New. - 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.
- Handle the Custom Error in the Main Function: Check if the error is not
niland handle it appropriately. - Display the Result: Use
fmt.Printlnto 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
ErrNotPositivevariable is defined usingerrors.Newto 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
checkPositivefunction 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.
- If the number is not positive (i.e., it is zero or negative), the function returns the custom error
Step 4: Handle the Custom Error in the Main Function
- The
mainfunction callscheckPositiveand checks if the returned error is notnil.- If
erris notnil, it indicates that the number was not positive, and the program prints the custom error message. - If
errisnil, it means the number was positive, and the program prints a success message.
- If
Step 5: Display the Result
- The program uses
fmt.Printlnto 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.