Error Handling in Golang
-
Error handling is a crucial aspect of writing good and reliable code.
-
In Golang programming language, error handling is done using a simple and effective approach that encourages explicit error checking and propagation.
-
In this tutorial, we will cover various aspects of error handling in Go, including how to create, handle, and propagate errors.
Error handling in Golang:
-
In Golang, errors act like messages that tell us when something goes wrong.
-
These messages are just simple notes that our program gives us. When we're working with Golang, we can easily check if a task encountered an error by looking at these notes.
-
If we see an error note, we can decide what to do next, like trying a different approach or informing the user.
-
The basic structure of error handling involves checking if a function call returned an error and taking appropriate action.
Returning Errors from Functions:
When a function can return an error, it's a good practice to include an error return value as the last return value. The errors package is commonly used to create error instances.
Example:
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Output:
ERROR!
Error: division by zero
Creating Custom Errors:
We can create custom error types by implementing the error interface.
Example:
package main
import (
"fmt"
)
type CustomError struct {
Code int
Message string
}
func (e CustomError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}
func process(data int) (string, error) {
if data < 0 {
return "", CustomError{Code: 100, Message: "Negative value not allowed"}
}
return fmt.Sprintf("Processed: %d", data), nil
}
func main() {
result, err := process(-5)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result)
}
Output:
ERROR!
Error: Error 100: Negative value not allowed
Defer Statement:
The defer statement can be used to ensure that a function call is performed at the end of a function's scope, making it useful for cleanup and closing resources.
Example:
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("nonexistent.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
}
Output:
ERROR!
Error: open nonexistent.txt: no such file or directory
Panic and Recover:
In exceptional cases, we might want to halt the program with a panic. The recover
function is used to catch and handle panics, allowing the program to continue execution.
Example:
package main
import (
"fmt"
)
func process() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
panic("Something went wrong!")
}
func main() {
process()
fmt.Println("Program continues....")
}
Output:
Recovered: Something went wrong!
Program continues....
Remember that proper error handling improves the reliability and maintainability of our Golang programs.