×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the errors.New() function

Here, we are going to demonstrate the errors.New() function in Golang (Go Language).
Submitted by Nidhi, on March 24, 2021 [Last updated : March 04, 2023]

errors.New() function in Golang

Problem Solution:

In this program, we will return an error from a user-defined function using errors.New() to the calling function.

Program/Source Code:

The source code to demonstrate the errors.New() function is given below. The given program is compiled and executed successfully.

Golang code to demonstrate the example of errors.New() function

// Golang program to demonstrate the
// errors.New() function

package main

import "fmt"
import "errors"

func divide(num1 int, num2 int) (int, error) {

	if num2 == 0 {
		return 0, errors.New("Divide by zero")
	}
	return num1 / num2, nil
}

func main() {
	res, err := divide(10, 0)

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Result: ", res)
	}
}

Output:

Divide by zero

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In the main() function, we created a user-defined function Divide() that returns the "Divide by zero" error to the main() function and printed the appropriate message on the console screen.

Golang Reflection Programs »





Comments and Discussions!

Load comments ↻





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