Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Error Handling in Go

15. Error Handling in Go

Absolutely, error handling is a crucial aspect of writing reliable and robust programs. In Go, error handling is done explicitly through the use of error values and the 'error'  interface. Let's explore error handling in Go in detail, along with examples.

Error Handling in Go:

In Go, errors are represented by the built-in 'error' interface. An error is simply a value that implements the 'error' interface, which has a single method, 'Error() string', that returns the error message.

Returning Errors:

Functions that can potentially encounter errors return an error value as the last return value. Conventionally, the last return value is of type 'error'.

func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}

 

Checking for Errors:

After calling a function that returns an error, you should check the error value to handle possible errors.

result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}

 

Creating Custom Errors:

You can create custom error types by implementing the 'error' interface in your own types.

type MyError struct {
    Message string
}

func (e MyError) Error() string {
    return e.Message
}

func someFunction() error {
    return MyError{Message: "An error occurred"}
}

 

Using 'fmt.Errorf()':

The 'fmt' package provides the 'Errorf()' function to create custom error values.

func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero: %f / %f", a, b)
}
return a / b, nil
}

 

Panic and Recover:

Go provides 'panic()' and 'recover()' mechanisms to handle exceptional situations. However, these should be used sparingly for truly exceptional cases, as Go promotes error handling using return values.

func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
panic("Something went wrong")
}

 

Error Wrapping:

In more complex scenarios, you might want to provide additional context to errors. You can achieve this using the 'github.com/pkg/errors' package.

import "github.com/pkg/errors"

func openFile(filename string) error {
_, err := os.Open(filename)
if err != nil {
return errors.Wrap(err, "unable to open file")
}
return nil
}

 

Summary:

  • Errors in Go are represented by the 'error' interface.
  • Functions returning errors typically return an error value as the last return value.
  • Check error values using 'if err != nil' to handle errors.
  • Create custom error types by implementing the 'error' interface.
  • Use 'fmt.Errorf()' to create custom error values with formatted messages.
  • 'panic()' and 'recover()'are available for exceptional cases but should be used cautiously.
  • The 'github.com/pkg/errors' package provides enhanced error handling with context.

By understanding error handling techniques in Go, you can write code that gracefully handles unexpected situations and provides meaningful feedback to users or other parts of your application. This leads to more reliable and maintainable software.