Search code examples
goerror-handlingpanic

Why Go's bufio uses panic under the hood?


Reading the code from the bufio package I've found such things:

// fill reads a new chunk into the buffer.
func (b *Reader) fill() {
    ...
    if b.w >= len(b.buf) {
        panic("bufio: tried to fill full buffer")
    }
    ...
}

At the same time the Effective Go section about panic contains the next paragraph:

This is only an example but real library functions should avoid panic. If the problem can be masked or worked around, it's always better to let things continue to run rather than taking down the whole program.

So, I wonder, is the problem with a particular buffered reader so important to cause the panic call in the standard library code?


Solution

  • It may be questionable, but consider: fill is a private method, and b.w and b.buf are private fields. If the condition that causes the panic is ever true, it's due to a logic error in the implementation of bufio. Since it should never really be possible to get into that state in the first place (a "can't happen" condition), we don't really know how we got there, and it's unclear how much other state got corrupted before the problem was detected and what, if anything, the user can do about it. In that kind of situation, a panic seems reasonable.