Error handling in Go
Golang Concepts
Go: Error handling
Golang has a unique approach to error handling that emphasizes explicit handling and reporting of errors. Understanding how to write effective error handling code is essential for creating robust and reliable applications.
Errors are values that indicate an abnormal condition or unexpected behavior in a program. Go has a built-in
error
type, which is simply an interface that defines anError()
method that returns a string describing the error.
how to define and return an error in Go
Here's an example:
func divide(x, y float64) (float64, error) {
if y == 0 {
return 0, errors.New("division by zero")
}
return x / y, nil
}
here, we define a function called divide
that takes two float64 parameters and returns a float64 result and an error. If the second parameter is zero, the function returns an error with the message division by zero
. Otherwise, it returns the result of dividing the two parameters.
How to check errors in Go
To check for errors in Go, you typically use an if
statement to check if the error value is nil (indicating no error), like below -
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
here, we call the divide
function with parameters 10 and 0. Since the second parameter is zero, the function returns an error. We then check if the error is nil using an if
statement. Since the error is not nil, we print the error message. If the error were nil, we would print the result instead.
- Error messages in Go are usually written in lowercase and without any trailing punctuation.
- It's also common to define custom error types by implementing the
error
interface, which can provide more information about the error or make it easier to handle specific types of errors in a program.