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?
The panic() function in Go Language is similar to exceptions raised at runtime when an error is encountered. panic() is either raised by the program itself when an unexpected error occurs or the programmer throws the exception on purpose for handling particular errors.
When code panics, there's no way to recover. You could call panic! for any error situation, whether there's a possible way to recover or not, but then you're making the decision that a situation is unrecoverable on behalf of the calling code.
The panic! macro signals that your program is in a state it can't handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The Result enum uses Rust's type system to indicate that operations might fail in a way that your code could recover from.
Using a channel to return something is the only way you can guarantee to collect all return values from goroutines without overwriting them. There are multiple ways we can use the same return channels: We can use the return channel to indicate only the error. We can use it to return both the result and the error.
You should assume that a panic will be immediately fatal, for the entire program, or at the very least for the current goroutine. Ask yourself "when this happens, should the application immediately crash?" If yes, use a panic; otherwise, use an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With