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.)
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."
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.
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? ??
Recommended Posts