Home » Golang

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

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() 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: ")

Basic 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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.