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

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




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.