"Escaping" panic
s1 in Go (I mean, those which might be produced by the functions comprising the public API of your package) are to deal with errors programmers do. So, if your function gets a pointer to an object, and that can't be nil
(say, to indicate that the value is missing) just go on and dereference the pointer to make the runtime panic
itself if it happens to be nil
. If a function expects an integer that must be in a certain range, panic
if it's not in that range — because in a correct program all values which might be passed to your function are in that range, and if they don't then either the programmer failed to obey the API or they did not sanitize the value acquired from the outside which, again, is not your fault.
On the other hand, problems like failure to open a file or pefrorm some other action your function is supposed to perform when called correctly should not cause panic
s and the function should return an appropriate error instead.
Note that the recommendation for explicit checking for null
parameters in the functions of public APIs in .NET and Java code has different goal of making such kinds of errors sort-of more readable. But since 99% of .NET and Java code just lets all the exceptions propagate to the top level (and then be displayed or may be logged) it's just replacing one (generated by runtime) exception with another. It might make errors more obvious—the execution fails in the API function, not somewhere deeper down the call stack—but adds unnecessary cruft to these API functions. So yes, this is opinionated but my subjective opinion is: to let it just crash is OK in Go—you'll get a descriptive stack trace.
TL;DR
With regard to processing of run-time problems,
-
panic
s are for programming errors;
- returning errors is for problems with carrying out the intended tasks of functions.
1 Another legitimate use for panic
s is quick "cold-path" returning from deep recursive processing/computation; in this case panic
should be caught and processed by your package, and the corresponding public API functions should return errors. See this and this for more info.