Go provides two ways of handling errors, but I'm not sure which one to use.
Assuming I'm implementing a classic ForEach
function which accepts a slice or a map as an argument. To check whether an iterable is passed in, I could do:
func ForEach(iterable interface{}, f interface{}) {
if isNotIterable(iterable) {
panic("Should pass in a slice or map!")
}
}
or
func ForEach(iterable interface{}, f interface{}) error {
if isNotIterable(iterable) {
return fmt.Errorf("Should pass in a slice or map!")
}
}
I saw some discussions saying panic()
should be avoided, but people also say that if program cannot recover from error, you should panic()
.
Which one should I use? And what's the main principle for picking the right one?
isNotIterable(iterable)
. Error would be appropriate. – jeevatkm Jun 12 '17 at 18:09main
function it is ok to use panics. Errors in all other cases. In libraries that are used in several other programs it is really 'forbidden' to use panic. – RickyA Jun 12 '17 at 18:29