0

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?

Chauvet
  • 63
  • 5
  • 1
    "Will I get a panic?" Maybe. Just **don't** do that. It is _dangerous_ and _not_ _useful_. – Volker Dec 31 '20 at 10:42
  • 1
    Could you please give me some reference to clarify why not to do that? – Chauvet Dec 31 '20 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 '20 at 10:50
  • Accurate!@Volker – Chauvet Dec 31 '20 at 10:59
  • Will it close rows automatically when an erorr occurs? – Chauvet Dec 31 '20 at 11:09
  • 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 '20 at 11:10
  • Is there any case that the rows is not nil but err exists, in which rows need to be closed?@mkopriva – Chauvet Dec 31 '20 at 11:28
  • 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 '20 at 16:23

1 Answers1

5

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)?

icza
  • 389,944
  • 63
  • 907
  • 827
  • Could you please give me some links to get those rules which I didn't find in official document? – Chauvet Dec 31 '20 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 '20 at 10:54