What are the cases where you would prefer a panic over an error? (and potentially an associated recovery?)
As I understand (I could be wrong): A well handled error is better than a panic. Therefore it would be good to hear about some use cases.
None I guess, right now I can't think of any case where I'd prefer panics. Since panics are errors you weren't able to handle, like using a field of a nil struct, or an slice with invalid index. Generally these are what I face and what the both have in common is that the compiler cannot pre-detect such errors so it panics when they occur.
Thanks, that makes sense. Do you professionally always have to recover those unexpected panics, Or would you allow them to crash.
Here’s a good article/blog post about that topic: https://eli.thegreenplace.net/2018/on-the-uses-and-misuses-of-panics-in-go/ Rob's quote is also quite good there.
Well I barely recover from panics, I fix the cause instead. The reason is that I find it challenging, guess for example your app panics in the middle of two database queries, if you recover there and recall the function you might have duplicate data in the database. You should handle that separately. Now assume you have a large user base with more than a thousand active users, if you recover from panic and some operations get to complete to some point before the panic, a disaster might happen. You can have a recover from panic but only to show users that an error with system was found and they have to wait for an update. As well as reporting somewhere about the panic and stack trace of the cause.
Panics should rather not be recovered. A goroutine panics when it doesn't know what to do, hence it "panics"
https://github.com/uber-go/guide/blob/master/style.md#dont-panic This may help you as well
I am just now catching up with the discussion from last week. Thank you for your replies: @Falling_inside_The_Black @Romshark @ali_error @mxrkw
Обсуждают сегодня