Introduction
The concept of errors is available in every programming language. You must have come across a situation where your code does not run, and an error is thrown. Errors indicate a condition where something is wrong in our program.
Errors are defined as unwelcome and unusual conditions that occur in the program. It can be at the compile or run time. Accessing a non-existent file, a failed database connection, or unusual user inputs are a few examples.
In this article, we will first discuss the error in Go and then the ways to handle the errors that can occur in our program.
Errors
We have already discussed the definition of errors. Errors are unavoidable in any program. An error indicates if something unexpected occurs. Errors also contribute to code stability and maintainability. Without errors, today's programs would be extremely buggy due to a lack of testing.
Error Interface
type error interface {
Error() string
}
It only has one method with the signature Error() string. This method returns an error description.
When printing the error, the fmt.Println function internally calls the Error() string method to obtain the error description.
Example:
package main
import "fmt"
func main() {
// trying to divide a number by zero will
// throw an error
fmt.Println(5/0)
}
Output:
./main.go:9:18: division by zero
Before we move on to discuss error handling, let's first discuss some ways to create errors in Go.
Using New Function
The errors package in Go has a function called New(). The New() function can be used to create errors.
Syntax:
errors.New(string message)
Example:
package main
//import fmt and errors package
import (
"fmt"
"errors"
)
//function to determine
//whether the person is atleast 18 years of age
func isEligibleVoter(age int) (int, error) {
if age < 18 {
return -1, errors.New("You are not eligible to vote!") //this is how error is thrown
} else {
return 1, nil
}
}
//main() function which calls the other function
func main() {
ok, err := isEligibleVoter(13)
if err != nil {
fmt.Println(err, ok)
} else{
fmt.Println("You can vote...")
}
}
Output:
You are not eligible to vote! -1
Using fmt.Errorf()
In the Go programming language, the fmt.Errorf() function allows us to use the formatting features to create descriptive error messages. The function is available in the fmt package.
Example:
// Including the main package
package main
// Importing fmt
import (
"fmt"
)
// Calling main
func main() {
data :=0.7
percentage :="percent"
// Calling the Errorf() function
//%f for float type and %s for string
err := fmt.Errorf(" There is %f %s error in the data.", data, percentage)
// Printing the error message
fmt.Println(err)
}
Output:
There is 0.700000 percent error in the data.