Chapter 12. back on your feet: Recovering from Failure
Every program encounters errors. You should plan for them.
Sometimes handling an error can be as simple as reporting it and exiting the program. But other errors may require additional action. You may need to close opened files or network connections, or otherwise clean up, so your program doesn’t leave a mess behind. In this chapter, we’ll show you how to defer cleanup actions so they happen even when there’s an error. We’ll also show you how to make your program panic in those (rare) situations where it’s appropriate, and how to recover afterward.
Reading numbers from a file, revisited
We’ve talked about handling errors in Go quite a lot. But the techniques we’ve shown thus far don’t work in every situation. Let’s look at one such scenario.
We want to create a program, sum.go, that reads float64
values from a text file, adds them all together, and prints their sum.
In Chapter 6 we created a GetFloats
function that opened a text file, converted each line of the file to a float64
value, and returned those values as a slice.
Here, we’ve moved GetFloats
to the main
package and updated it to rely on two new functions, OpenFile
and CloseFile
, to open and close the text file.
We want to specify the name of the file we’re ...
Get Head First Go now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.