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 »



Comments and Discussions!

Load comments ↻





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