DEV Community

nadirbasalamah
nadirbasalamah

Posted on • Edited on

Golang tutorial - 8 Error Handling

Error Handling in Go

Error handling is a common thing when creating software. Error handling is really useful to handle errors that occur in software to make software more reliable to use. In the Go programming language, the error handling is straightforward. Instead of using try catch block, the error handling mechanism in Go is performed if the error occurred.

Printing an error

There are four common ways to check an error that occurred in Go. An error can be checked by this syntax:

  • fmt.Println("Error occured: ",err)
  • log.Println(err)
  • log.Fatalln(err)
  • panic(err)

Here is the example of error handling in Go:

func main() {
    //read a file called test.txt that isn't exist
    _, err := os.Open("test.txt")
    if err != nil {
        fmt.Println("Error occured: ", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Error occured:  open test.txt: The system cannot find the file specified.
Enter fullscreen mode Exit fullscreen mode

Based on that code, the error message can be printed using fmt.Println().

Let's change it with another syntax.

func main() {
    //read a file called test.txt that isn't exist
    _, err := os.Open("test.txt")
    if err != nil {
        log.Println("Error occured: ", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

2020/06/25 13:26:23 Error occured:  open test.txt: The system cannot find the file specified.
Enter fullscreen mode Exit fullscreen mode

Based on that code, the log.Println() syntax, not only prints out the error message but also prints out the date and time when the error occurred.

Let's change it with another syntax.

func main() {
    //read a file called test.txt that isn't exist
    _, err := os.Open("test.txt")
    if err != nil {
        log.Fatalln("Error occured: ", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

2020/06/25 13:27:25 Error occured:  open test.txt: The system cannot find the file specified.
exit status 1
Enter fullscreen mode Exit fullscreen mode

Based on that code, the log.Fatalln() syntax, prints out the error message with date and time but the code is also exited with status code equals 1.

Let's change it with another syntax.

func main() {
    //read a file called test.txt that isn't exist
    _, err := os.Open("test.txt")
    if err != nil {
        panic(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

panic: open test.txt: The system cannot find the file specified.

goroutine 1 [running]:
main.main()
        D:/XAMPP/htdocs/learn_go/src/review-again/main.go:11 +0x6a
exit status 2
Enter fullscreen mode Exit fullscreen mode

Based on that code, the code prints out an error message, and the code is exited with status code equals 2.

Create a custom error handling

In Go, custom error handling is also available with the errors.New() syntax. Here is an example.

func main() {
    //calculate a division of two number with zero
    //ignore the result by using _ notation
    _, err := divide(4, 0)
    if err != nil {
        log.Println("Error occured: ", err)
    }
}

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}
Enter fullscreen mode Exit fullscreen mode

Output:

2020/06/25 13:40:30 Error occured:  cannot divide by zero
Enter fullscreen mode Exit fullscreen mode

Based on that code, the errors.New() returns a error type that can be used inside this code.
Custom error handling is also available by creating a struct that implements a method Error() from the error interface.

type customErr struct {
    a float64
}

//Implements Error() method so the customErr struct is a type of error
//Basically customErr struct is a error type
func (c *customErr) Error() string {
    return fmt.Sprintf("Cannot find square root of negative number: %v", c.a)
}

func main() {
    _, err := squareRoot(-16)
    if err != nil {
        log.Println("Error occured: ", err)
    }
}

func squareRoot(a float64) (float64, error) {
    if a < 0 {
        return 0, &customErr{a}
    }
    return math.Sqrt(a), nil
}
Enter fullscreen mode Exit fullscreen mode

Output:

2020/06/25 13:51:07 Error occured:  Cannot find square root of negative number: -16
Enter fullscreen mode Exit fullscreen mode

Based on that code, custom error can be created with a struct that implements an error interface's method called Error().

Notes

  • Interesting statement about error handling in Go, check out here

I hope this article is helpful to learn the Go programming language. If you have any thoughts or feedback, you can write it in the discussion section below.

Top comments (0)