Q:

Golang program to demonstrate the errors.New() function

belongs to collection: Golang Reflection Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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

// 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Golang program to demonstrate the use of fallthrou...