How to return an error in Golang?

Golang | returning an error: Here, we are going to learn how to return an error in Golang?
Submitted by Anshuman Singh, on July 14, 2019 [Last updated : March 05, 2023]

In Golang, we return errors explicitly using the return statement. This contrasts with the exceptions used in languages like java, python. The approach in Golang to makes it easy to see which function returns an error?

In Golang, errors are the last return value and have type error, a built-in interface.

errors.New()

errors.New() is used to construct basic error value with the given error messages.

We can also define custom error messages using the Error() method in Golang.

How to create an error message in Golang?

Syntax

    err_1 := errors.New("Error message_1: ")
    err_2 := errors.New("Error message_2: ")

Golang program to test an error in Golang

package main

import (

    "fmt"
    "errors"

)

func test(value int) (int, error) {

    if (value == 0) {

        return 0, nil;

    } else {

        return -1, errors.New("Invalid value: ")

    }
}

func main() {
    value, error := test(10)
    fmt.Printf("Value: %d, Error: %v", value, error)

    value, error = test(0)
    fmt.Printf("\n\nValue: %d, Error: %v", value, error)
}

Output

Value: -1, Error: Invalid value: 

Value: 0, Error: <nil>


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.