Open In App

errors.New() Function in Golang with Examples

Last Updated : 03 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




// 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)
    }
}


Output:

Sample Error

Example 2:




// 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)
    }
}


Output:

It Says Error!

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads