Error Handling in Golang

Learn via video courses
Topics Covered

Overview

The error handling in the Go language is very different from that of other languages like Java, C++, Python, etc. The built-in errors of the Go language do not have a regular try/catch method, instead, they are returned by a function.

What are the Errors in Golang?

The go language does not have any exception handling mechanism like try/catch in Java. A go way to handle errors is:

  • functions to return
    • nil if no error occurred
    • an error object as their only or last returned value
  • And calling functions to always check the error they receive and notify the user

Representation:

Example:

Explanation:

In this example, the file named filename.txt is opened and the if condition is used for checking if there is any problem while opening the file. If there is any error while opening the file then it simply returns the error else the file is opened.

Command line arguments:

To access command line arguments:

  • We need to import os package
  • Access the arguments via Args[1], Args[2],...

Extract Information from Errors in Golang

When an execution error occurs (eg: index an array out of bounds) program crashes and Go runtime triggers a runtime panic.

Panic can also be initiated from code directly using the panic() function. It takes as input one argument to be printed when the program dies. Recovery from a panic can be done using the recover() function, which helps to regain control of a panicking function, stop the terminating sequence and resume normal execution.

Note: recover is only useful when called inside a deferred function.

Example:

Output:

Explanation:

In this example, the code checks if the number entered by the user for dividing two numbers is valid or not. Here the variables used are a and b. If the value of b, which is in the denominator is zero then it returns a message that says that b should not be 0. If both the values are correct then it divides the two numbers and the answer is returned at the output.

Args[0] returns the name of the program getting executed If the arguments are less than required then we get - panic: run time error: index out of range

Create Custom Errors in Golang with Examples

Constructing Errors

In the Go language, the errors can be constructed by using the built-in package of Go which is fmt or errors. For instance, look at the example given below, in this the function uses the package error to return a new error along with the static error message.

It is the same for packages like fmt as well. The fmt package is used for adding the dynamic data to the output error like for data type, string, int, or any other error for that matter.

Let's take one more example to understand this better:

The following are the things that should be noted in this example:

The error at the output can be returned as nil as a default or a zero value of an error in the Go language. The error is generally returned as the last argument in a function, therefore, if we look at the example given, we can see that the order of the argument is int and then the error in the argument.

Defining Expected Errors

This is another yet important technique in Go language for defining the errors that are expected and is checked for other parts of the code explicitly. This is only useful when another branch of code needs to be executed to check if certain types of errors are encountered or not.

Defining Sentinel Errors:

By using the earlier divide function, we can improve the displaying of the error by pre-defining the error ‘sentinel’ and by calling the function explicitly for checking this error by using errors. Is.

Output:

Explanation:

In this example, the variable ErrDivideByZero is assigned with the New type. The divide function checks if the two variables are valid or not. If variable b is zero then you can't divide and hence the error ErrDivideByZero is thrown at the output. If there are any other errors then the default error of the switch case is executed.

Defining Custom Error Types:

It is used when we need additional functionality like an additional data field or the error message that prints dynamic value when displayed. To understand how to define custom error types, let’s look at the example given below:

Output:

Explanation:

In this example, we will notice that the new type DivisionError implements the error interface by using errors. A for checking and converting the standard error to display a more specific error DivisionError.

Handle Errors in Golang

Using New() Function

We can make error-type with function errors.New(“appropriate error msg”) which is available from the error package. Another way of generating an error object is using the fmt.Error() function.

Implementation:

Output as an example:

Using Errorf() Function

Implementation:

Output as an example:

Conclusion

  • The error handling in the Go language is very different from that of other languages like Java, C++, Python, etc. The built-in errors of the Go language do not have a regular try/catch method, instead, they are returned by a function.
  • The go language does not have any exception handling mechanism like try/catch in Java. A go way to handle errors is:
    • for functions to return
      • nil if no error occurred
      • an error object as their only or last returned value
  • And calling functions to always check the error they receive and notify the user