-2

Here is typical use case.

rows, err := db.Query(`...`, ...)
if err != nil{
    return
}
defer rows.Close()
...

Here is what I want to use.

rows, err := db.Query(`...`, ...)
defer rows.Close()
if err != nil{
    return
}
...

Will I get a panic?

8
  • 1
    "Will I get a panic?" Maybe. Just don't do that. It is dangerous and not useful.
    – Volker
    Dec 31, 2020 at 10:42
  • 1
    Could you please give me some reference to clarify why not to do that?
    – Chauvet
    Dec 31, 2020 at 10:46
  • 3
    Don't do that as rows can be nil or otherwise invalid. Just don't do that. That is reference enough.
    – Volker
    Dec 31, 2020 at 10:50
  • 2
    @Chauvet there are no rows to close when an error occurs. When an error occurs the primary return value is nil, why would you want to close that? and how would you do it without causing panic?
    – mkopriva
    Dec 31, 2020 at 11:10
  • 1
    @Chauvet It seems like you're hard-set on doing what you've already decided you want to do, regardless of the responses you received. You want to call rows.Close before error checking but also avoid panics? You can check if rows is not nil and if it isn't call rows.Close, after that block check the error value. Ultimately it is your code, you do whatever you want however you want...
    – mkopriva
    Dec 31, 2020 at 16:23

1 Answer 1

4

It may or may not panic. General rule is to always check the returned error first, and if that is nil, only then proceed to use other return values.

If you get a non-nil error, other return values are "undefined", they may be nil, and thus calling their methods may easily result in a runtime panic.

There may be exceptions of course which are usually documented, e.g. http.Get() may return an error and a non-nil response if following redirection fails, providing details about the error. But this is rare, and should always be documented. DB.Query() does not document such deviation, so you can't rely on that.

See related: Do we need to close the response object if an error occurs while calling http.Get(url)?

2
  • Could you please give me some links to get those rules which I didn't find in official document?
    – Chauvet
    Dec 31, 2020 at 10:48
  • 3
    @Chauvet This isn't written in stone and you could write code that behaves otherwise (e.g. returns valid results and non-nil errors), this is just common sense not to do.
    – icza
    Dec 31, 2020 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.