Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Agreed, you should be using defer, not recover.

The canonical examples are closing a file and releasing a mutex. Both have code samples here: http://blog.golang.org/defer-panic-and-recover

I'm confused as to what you guys are saying: are you saying that you don't need to handle exceptions (whether using defer or recover), or that it's better to use defer over recover? I take exception to the former, totally agree with the latter.



defer and recover have nothing to do with each other, except that in the few circumstances where it's appropriate to use recover, you often do it within a defer block.

    > are you saying that you don't need to handle exceptions 
    > (whether using defer or recover)
Go doesn't have exceptions. You don't need to handle (i.e. explicitly deal with) panics via recover. If you do, especially if you're not making the panics yourself in e.g. a parsing package, that's a bad code smell and you're probably doing something wrong.


defer doesn't "handle" panics. It won't stop your program from crashing. You have serious gaps in your knowledge on this subject.


My understanding is that defer is the broad equivalent of a Java finally block, and recover is the broad equivalent of a Java catch block. I think of both as ways of handling exceptions, although I see how the word "handle" could be interpreted in a way that makes my statements nonsensical. By handling I meant "doing the right thing", not "swallowing the panic/exception"; I apologize for the ambiguity you found.

If you do still think I have gaps in my knowledge, I humbly suggest that you briefly fill in those gaps with facts; it should save you time in the long run and will likely win you a few converts!


You're looking at it wrong. Stop thinking about Java. Go programmers rarely use recover. There are many that have probably never used it at all. Go does not have exceptions. Panics are only vaguely like exceptions, but you shouldn't even think about them in those terms. It is confusing you badly.

Defer is primarily used to make sure that clean-up happens in functions that have multiple exit points (return statements). It's a convenient side effect that defers are executed while a panic unwinds the stack, but it is rarely the first thing on the mind of the Go programmer when they type "defer".

Embrace error values. Return them! Check them! Panic when shit goes really bad. That's it. If you're writing Go code and you're thinking about "throw" "catch" or "finally", you're doing it wrong. Go's features do not map cleanly to those concepts, because Go doesn't have exceptions.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: