ADVERTISEMENT
ADVERTISEMENT

Does Go language have exception handling?

Learn what are the exceptions in Go language, does Go language have exception handling?
Submitted by IncludeHelp, on October 04, 2021

Let's understand, what is an exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program.

Now coming to the question, does Go language have exception handling?

The answer is - No, the Go language does not have the concept of expectations handling, it has a different approach. For the plain error handling – we can use the multi-value returns approach to report and return an error. Go code uses error values to indicate an abnormal state.

Consider the below example – here we are trying to open a file that does not exist.

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.ReadFile("myfile.txt")
	// If there is an error
	if err != nil {
		fmt.Println("File does not exist\nThe Error is:", err)
		os.Exit(0)
	}

	// If file exists then  print the content
	fmt.Println("The file's content is:")
	os.Stdout.Write(f)
}

Output:

File does not exist
The Error is: open myfile.txt: no such file or directory

Golang FAQ »

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.