官术网_书友最值得收藏!

Error handling in Go

Errors happen all the time, so it is our job to both catch and handle them, especially when writing code that deals with sensitive system information and files. The good news is that Go has a special data type called error that helps signify erroneous states; if an error variable has a nil value, then there is no error situation.

As you saw in the addCLA.go program that was developed in the previous chapter, you can ignore the error variable that is returned by most Go functions using the _ character:

temp, _ := strconv.Atoi(arguments[i]) 

However, this is not considered good practice and should be avoided, especially on systems software and other kinds of critical software, such as server processes.

As you will see in Chapter 6, File Input and Output, even End of File (EOF) is a type of error that is returned when there is nothing left to read from a file. As EOF is defined in the io package, you can handle it as follows:

if err == io.EOF {

// Do something }

However, the most important task to learn is how to develop functions that return error variables and how to handle them, which is explained next.

主站蜘蛛池模板: 若尔盖县| 云阳县| 阳春市| 介休市| 石景山区| 青铜峡市| 太白县| 马龙县| 商丘市| 常州市| 涿州市| 留坝县| 南乐县| 垣曲县| 郯城县| 碌曲县| 曲沃县| 潼南县| 苏州市| 铅山县| 临桂县| 长治县| 惠来县| 久治县| 南靖县| 邻水| 平凉市| 五莲县| 沂南县| 阳信县| 淮北市| 建瓯市| 东港市| 卓资县| 苍南县| 绥化市| 额济纳旗| 许昌市| 五寨县| 西安市| 凤山县|