Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use panic or return error?

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?

like image 756
laike9m Avatar asked Jun 12 '17 16:06

laike9m


People also ask

What is panic error?

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.

Can you recover from panic Rust?

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.

What does panic do in Rust?

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.

How do you handle a Goroutine error?

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.


1 Answers

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.

like image 124
Adrian Avatar answered Sep 29 '22 19:09

Adrian