errors.New() Function in Golang with Examples

Errors package in Golang is used to implement the functions to manipulate the errors. errors.New()function returns an error that formats like given text. Each call to New returns distinct error value indeed in the event that the content is indistinguishable.

Syntax:

func New(text string) error

It returns an error.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// the errors.new() function 
package main
  
import (
    "errors"
    "fmt"
)
// Main function
func main() {
    err := errors.New("Sample Error")
    if err != nil {
        fmt.Print(err)
    }
}

chevron_right


Output:

Sample Error

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// the errors.new() function
package main
  
import (
    "errors"
    "fmt"
)
  
// Main function
func main() {
    err := errors.New("It Says Error!")
    if err != nil {
        fmt.Print(err)
    }
}

chevron_right


Output:

It Says Error!
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.