Signup/Sign In
PUBLISHED ON: FEBRUARY 17, 2023

Error handling in Golang

Handling errors is an essential part of writing good code. It makes debugging easier for other users who use our program. Error handling is required for creating Go modules. Golang does not use conventional methods like other programming languages like java (try...catch...finally block) or python (try...except...finally block). It uses a completely different approach to handle errors.

To deal with errors we need to import the errors module from the Golang library. Package errors implements functions to manipulate errors. Here is the basic usage example to explain how to use errors lib:

package main

import (
	"errors"
)

func printf() error {
	return errors.New("Something didn't work as expected.")
}

To pop a new error with a message, we use this Syntax: errors.New("STRING")

Example: greetings message program in Golang

Let's keep things simple and use code from our previous tutorial with errors lib to learn more about error handling.

package main

import (
	"fmt"
)

func main() {

	fmt.Println("Hello World")

}

Now we can create a program to get users input their name and greeted with a message.

Here, we have used Scanln() to get input from the user and save it in the user_name variable without using errors.

package main

import (
	"fmt"
)

func main() {
	
	fmt.Println("Hello stranger, type your name here:")
	
	// Define the variable user_name of type string
	var user_name string
	
	// Take user_name as input
	fmt.Scanln(&user_name)
	
	// If the user_name is an empty string then print a message.
	if user_name == "" {
		fmt.Println("Name cannot be empty")
	} else {
		// Greeting message
		fmt.Println("Hey " + user_name + ", welcome to Golang!")
	}
}

Output:

Hello stranger, type your name here:

Name cannot be empty

Define errors in Golang

Now let's import the errors package from Golang standard library and use errors.New() function to return an error that formats as the given text.

package main

import (
	"fmt"

	//manipulate errors.
    "errors"
)

func main() {
	
	fmt.Println("Hello stranger, type your name here:")
	
	// Define the variable user_name of type string
	var user_name string
	
	// Take user_name as input
	fmt.Scanln(&user_name)
	
	// If the user_name is an empty string then print a message.
	if user_name == "" {
		
		// panic an error if the name is empty.
		panic(errors.New("Name cannot be empty"))

	} else {
		
		// Greeting message
		fmt.Println("Hey " + user_name + ", welcome to Golang!")
		
	}
}

Output:

You can see the output has exit code 1.

Hello stranger, type your name here:

panic: Name cannot be empty

goroutine 1 [running]:
main.main()
        /tmp/gop/main.go:24 +0x155
exit status 2

Conclusion

In this tutorial, you have learned about what the program should do if there is an error while running the Golang program. Golang (as opposed to Java or Python) does not use conventional exceptions.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.