Panicking when necessary
Most of the time, deciding whether to panic or to return an error is not an easy decision. This recipe offers some guidelines to make that decision easier.
How to do it...
There are two situations where you can panic. Panic if either of the following is the case:
- An invariant is violated
- The program cannot continue in the current state
An invariant is a condition that cannot be violated in a program. Thus, if you detect that it is violated, instead of returning an error, panic.
The following example is from a graph library I wrote. A graph contains nodes and edges, managed by a *Graph
structure. The Graph.NewEdge
method creates a new edge between two nodes. Those two nodes must belong to the same graph as the receiver of the NewEdge
method so it is appropriate to panic if that is not the case, as follows:
func (g *Graph) NewEdge(from,to *Node) *Edge { if from.graph!=g { panic("from...