About Go error handling * This is a rough article.

Go has no exception mechanism, but you can implement the following error handling by taking advantage of the feature that the function can return multiple return values.

python


	result, err := method()
	if err != nil {
		//Error handling
		log.Fatal(err)
	}

"Oh, that's right. For the time being, error handling should be written like this." I feel that there is no problem with this level of understanding, but I was curious about it somehow, so I will summarize it. (* It didn't come together after all.)

What is the exception mechanism in the first place?

In VB.NET used in practice, exception handling is implemented as follows.

python


try {
processing
} catch (Exception class variable) {
Exception handling
} finally{
Post-processing
}

What is the exception mechanism? I wrote that, but if you apply it to the syntax, you can implement error handling. That syntax doesn't exist in Go. It's fatal that you can't handle errors! !! However, that is not the case, and error handling can be implemented in Go as well. One of them is the one described first, and the second variable determines the presence or absence of an error. This is an idiom (like an English idiom), so maybe it's just like "Oh, that's right."

I actually tried it

The following code will open foo.txt in the same hierarchy as main.go as read-only.

main.go


package main

import (
	"log"
	"os"
)

func main() {
	f, err := os.Open("foo.txt")
	if err != nil {
		log.Fatal("err")
	}
	log.Fatal("ok")
	defer f.Close()
}

When I renamed the file to hoge.txt and got an error, I tried to see what was in the err.

image.png

For the time being, it seems okay if you remember that if there is an error, something other than nil will be entered. Is it OK that the second return value returned by the function is always information about the error? ??

Summary

It wasn't organized. For the time being, I will continue to spend time after tomorrow with "Oh, that's right. For the time being, I should write error handling like this."

Recommended Posts

About Go error handling * This is a rough article.
About February 02, 2020 * This is a Python article.
About tweepy error handling
About FastAPI ~ Endpoint error handling ~
Is this string a decimal?
Is this a system trade?
This is a webiopi question
i! i! ← This is a mathematical formula
A story about a 503 error on Heroku open
Pythonista tells us "This is strange Go language"