Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
Odds are that most unchecked deferred Close's are exactly the kind of things errcheck should report.
Consider the following piece of code:
This is clearly a Close that can return an error that should be checked. Same goes for closing database transactions.
If you want to hide specific Close's, that are known to always return nil, consider using the
I would argue that in your snippet it is important to check and handle the error from f.Write - and maybe less important to check the result of f.Close() as it is anyway executed at the end of the function call and the variable f will get deallocated anyway.
Consider also the documentation and example from http://golang.org/pkg/net/http/ - it does not use error checking for closing the response body:
Of course the defaults can be set in different ways and there are tradeoffs involved - personally, I find its too bad that the default output gets polluted with many of "defer r.Body.Close()".
For reference, you can check for errors as described in the answer to http://stackoverflow.com/questions/19934641/golang-returning-from-defer
Closing the response body of an HTTP request you only read from cannot yield a meaningful error, no, and closing here is done to return the connection to the pool.
My example, however, wasn't using HTTP, but files. If you write to a file, and that write didn't return an error, closing the file can still return an error indicating that the write itself failed. Why? caching by the OS, for one. So if you don't check that Close's error, you're writing buggy code that can potentially lose data.
Also I'm not sure what that question on SO has to do with this. We're not panicing, nor recovering panics. And if you wanted to check the error return of Close in a defer, you'd do so in a way that errcheck wouldn't complain about, such as
(left out error handling of os.Create for brevity, not correctness.)