error handling in Go

Error Handling in Go

March 25th, 2026
1834
6:00 Minutes

Error handling in Golang is done through returning error values rather than using try-catch like in Python or in Java. This method makes sure of handling explicit errors, improving code clarity and control. This blog will give an in-depth understanding on error handling in Go, what it is, why it is needed, creating and returning errors in Go and so much more. So let's get into it.

What is Error Handling in Go?

The error handling in Go is done through treating errors as values returned from functions, instead of using a 'try-catch' method. At the same time, the standard approach is for multiple return values, where the last value is of the 'error' interface type, which is built in. Here is an example given, which will help you understand it in an easy way.


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)
}

Explanation:

Here in Golang, errors are handled explicitly through the 'error' type. The 'divide' function returns two values, the result and an 'error'. These are considered 'nil' if no error is shown. Here, if 'b' is zero, it returns an error through 'errors.New'. Whereas in main, we check whether 'err' is not 'nil'. If it actually is, we handle the error (print it and exit), or else we put the result to use. The example's pattern encourages explicit error checking and makes code stronger. Here is the output of this example.


Error: division by zero

Why is Error Handling Required?

Now, you might be wondering why is error handling required in Go? It is needed to make sure of the reliability, strength and maintainability of applications. Golang's design cheers explicit error handling which is different from the exception-based mechanisms which are found in every other language. Read on to have an in-depth understanding on why error handling in Go is required.

  • Reliability and Explicitness

Golang's philosophy highlights making error handling an integral part of the code logic. Through returning errors as values, Golang forces developers to check for explicitly and address potential threats after every function call. It prevents errors from being silently ignored or implicitly grown, which leads to more reliable applications that fail fast and predictably.

  • Maintenance

The explicit and predictable error handling makes Go code easier to manage over time. Developers can quickly locate potential error points and understand how they are being managed, easing up the procedure of debugging and refining the codebase.

  • Clear Debugging Information

Golang's error handling design eases up the clear debugging. Errors that are values can be wrapped with additional context like function names, parameters or other related information. These give more insight into the cause of a failure without the need to sift through tough stack traces.

  • Preventing Catastrophic Failures

In serious systems like network applications or concurrent programs, unhandled errors may lead to serious consequences. Golang's emphasis on explicit error checking assists in preventing these catastrophic failures by making sure that the errors are addressed at their source.

  • Control and Clarity

Golang's error interface offers an easy yet strong mechanism of representing errors with its single 'Error() string' method. This method avoids tough exception hierarchies and permits for direct manipulation and checking of error values, providing developers with elegant control over the error management.

Read Also: Golang Tutorial- Learn Go Programming Language

The Error Type in Go

The error type in Golang is basically an interface type. The error variable shows any value that can define itself as a string. Take a look at the declaration of the interface.


type error interface {
    Error() string
}

Here, the error type with all in-built types is predeclared in the universe block. Now, let us go through an example to make things easier for you to understand the error type in Go.


package main

import (
	"errors"
	"fmt"
)

func checkAge(age int) (string, error) {
	if age < 18 {
		return "", errors.New("age must be 18 or older")
	}
	return "Access granted", nil
}

func main() {
	result, err := checkAge(16)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(result)
}

Explanation:

Here in Golang, the 'error' type is an interface which is used to represent errors. The 'errors.New' function makes a basic error with a custom message. Here, the 'checkAge' function returns a string and an 'error'. If the 'age' is below 18, it returns an error, otherwise it returns a successful message with 'nil' error. In 'main', we check whether 'err' is not 'nil'. If an error is there, we print it and exit, or else we print the result. This explicit error handling through the 'error' type is the main part of Go's design for reliable code. Below is the output for this example.


Error: age must be 18 or older

Creating and Returning Errors in Go

Golang's errors are basically values which implement the in-built error interface. This interface represents single method:


type error interface {
    Error() string
}

The above shows that any type which implements an 'Error()' method returning a string can be taken as an error.

In Golang, errors are created and returned to manage issues in a program.

  • Creating Errors: You can use 'errors.New(“error message”) for creating a simple error with a custom message.
  • Returning Errors: Functions usually return an 'error' type as the last return value. Must return to 'nil' if there is no error.
  • Handling Errors: You must check if the error is 'nil'. And if it is not, then handle the error like log it, or else just proceed with the result.

Now, let us understand returning and creating errors in Go through an example, to make things easier for you to understand.


package main

import (
	"errors"
	"fmt"
)

// Function that may return an error
func divide(a, b float64) (float64, error) {
	if b == 0 {
		// Create and return an error
		return 0, errors.New("division by zero")
	}
	return a / b, nil // Return result and no error
}

func main() {
	// Example 1: Valid division
	result, err := divide(10, 2)
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Result:", result) // Output: Result: 5
	}

	// Example 2: Division by zero
	result, err = divide(10, 0)
	if err != nil {
		fmt.Println("Error:", err) // Output: Error: division by zero
	} else {
		fmt.Println("Result:", result)
	}
}

Here is the explanation of the example given above:

  • Creating an Error: The 'errors.New()' function makes a basic error with a custom message like 'division by zero'.
  • Returning an Error: The 'divide' function returns two values which are the result (float64) and an error (error). If no error comes, 'nil' is returned for the error.
  • Handling Errors: Here, in 'main', we check whether 'err' is not 'nil' to manage errors, or else we make use of the result.

The given example represents the Go convention of returning errors as a separate return value and checking them explicitly.

Examples

As we read about error handling in Go, let us take a look at some examples for you to understand this well.

Example 1: Basic Error Creation and Handling


package main

import (
	"errors"
	"fmt"
)

func checkAge(age int) (string, error) {
	if age < 18 {
		return "", errors.New("age must be 18 or older")
	}
	return "Access granted", nil
}

func main() {
	result, err := checkAge(16)
	if err != nil {
		fmt.Println("Error:", err) // Output: Error: age must be 18 or older
	} else {
		fmt.Println(result)
	}
}

Basic Error Creation and Handling

Explanation to this example:

  • Error Creation: 'errors.New' makes an error with a custom message if 'age<18'.
  • Returning Error: Here, the function returns a string and an 'error'. If there is not any error, then 'nil' is returned.
  • Handling Error: Here in 'main', we check whether 'err != nil' to print the error or the result.

Example 2: File Reading with Error Handling


package main

import (
	"fmt"
	"os"
)

func readFile(filename string) (string, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return "", err // Return the system error as-is
	}
	return string(data), nil
}

func main() {
	content, err := readFile("nonexistent.txt")
	if err != nil {
		fmt.Println("Error:", err) // Output: Error: open nonexistent.txt: no such file or directory
	} else {
		fmt.Println("Content:", content)
	}
}

Explanation:

  • Error Creation: 'os.ReadFile' returns an error if the file doesn't exist or can't be read.
  • Returning Error: Here, error is passed through directly, with an empty string as the result.
  • Handling Error: The 'main' function checks for 'err' and prints it if not 'nil', otherwise shows the file content.

Example 3: Custom Error with fmt.Errorf


package main

import (
	"fmt"
)

func getUser(id int) (string, error) {
	if id <= 0 {
		return "", fmt.Errorf("invalid user ID: %d", id)
	}
	return fmt.Sprintf("User-%d", id), nil
}

func main() {
	user, err := getUser(-1)
	if err != nil {
		fmt.Println("Error:", err) // Output: Error: invalid user ID: -1
	} else {
		fmt.Println("User:", user)
	}

	user, err = getUser(42)
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("User:", user) // Output: User: User-42
	}
}

Explanation:

  • Error Creation: 'fmt.Errorf' creates a formatted error message, including the invalid 'id'.
  • Returning Error: Returns an error for invalid IDs, or a user string and 'nil' for valid IDs.
  • Handling Error: The 'main' function checks 'err' to either print the error or the successful result.

Points To Remember:

  • Golang makes use of explicit error handling with 'error' type as a return value.
  • Must check errors with 'if err != nil' for handling issues.
  • Make use of 'errors.New' for easy errors or 'fmt.Errorf' for formatted messages.
  • You must always handle errors to prevent unexpected behavior.

Read Also: Top 50+ Golang Interview Questions And Answers

Wrapping Up

So basically, effective error handling in Go is simple yet powerful, relying on explicit error returns and clear control flow. Through making use of error types, if err != nil checks and custom errors when required, you can create robust, readable and manageable code. Adopt and embrace Go's straightforward approach to handle errors flawlessly and make sure your programs are resilient.

FAQs: Error Handling in Go

Q1. What is the work of error.Is it in Go?

It checks that a given error matches a particular error value. It's specially useful with wrapped or nested errors, letting us identify particular error types or sentinel errors in a chain of errors.

Q2. What is Panic in Golang?

panic() is either raised by the program itself when an unexpected error comes or the programmer throws the exception on purpose for handling specific errors.

Q3. What are handlers in Go?

It is an object applying the http.Handler interface. A well known way to write a handler is through using the http. HandlerFunc adapter on functions with the appropriate signature.

Q4. How do you implement Error Handling in Go?

You typically return an error from functions and check it using if conditions.

Q5. How do beginners practice error handling in Go?

Beginners can practice by writing functions that return errors, checking them with if err != nil, and handling different cases like file operations or network requests.

Course Schedule

Course NameBatch TypeDetails
Golang Training
Every WeekdayView Details
Golang Training
Every WeekendView Details
About the Author
Piyush Verma | igmGuru
About the Author

Piyush is a technical writer skilled in Golang, R, C, C#, C++, Ruby, and ERP systems. He simplifies complex coding concepts into clear, beginner-friendly content, helping readers build strong foundations. With a structured approach, he supports both beginners and professionals in mastering technologies and advancing their careers.

Drop Us a Query
Fields marked * are mandatory

Programming Certification Courses

×

Your Shopping Cart


Your shopping cart is empty.