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

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.

主站蜘蛛池模板: 樟树市| 和龙市| 溧阳市| 日土县| 什邡市| 拜泉县| 南皮县| 瑞丽市| 南雄市| 邵东县| 蓬溪县| 平舆县| 双桥区| 峡江县| 承德市| 镇远县| 敦化市| 石首市| 布拖县| 临汾市| 安平县| 广元市| 蓝山县| 武胜县| 潮安县| 凉山| 和龙市| 宜兰县| 喀喇沁旗| 余姚市| 卓资县| 高青县| 黄山市| 武强县| 大英县| 沁水县| 定陶县| 黎川县| 甘泉县| 道真| 定兴县|