3 ms·
Calling it error handling was actually a deliberate choice: since defer/panic/recover isn't an exception mechanism, it wouldn't have made sense to call it one.
by vilya 16y ago
Calling it error handling was actually a deliberate choice: since defer/panic/recover isn't an exception mechanism, it wouldn't have made sense to call it one.
What I've read about it so far is the original "Proposal for an exception-like mechanism" thread on the golang-nuts group [1]; and the "Panic, defer and recover" article referenced in the Go FAQ [2]. If any of the stuff below is misinformed, or just plain wrong, I'd love to hear: Go is a language that I want to like.
So now the things I object to:
With Go's model, as I understand it, you can call panic with an arbitrary value. To handle that reliably, your deferred block has to check the type and dispatch to appropriate handler code yourself. That's something you get for free with exceptions, where you can generally provide separate catch blocks for different types of exception.
When you recover from a panic, the execution of your function is over. So if you have two operations which can panic and you want to be sure both are attempted, you have to wrap each one in a separate function. It also means the only way to tell if a function panicked (in case you need to do further cleanup, say) is by checking the return code - and you'd better hope that everyone is following sensible conventions for what they return there.
That leads to another point: Go encourages checking return codes to see if a function failed, whether or not there was a panic. One of the big advances from exceptions, to my mind, was that you no longer had to mingle control flow information with application data. Keeping the two separate makes it easier to write reliable software because it's more self-documenting.
On a more subjective note, I find the syntax really clunky. The examples I've seen all seem to wrap the handler code in an anonymous function:
defer func() { ... }()
I imagine it would get pretty noisy if you were registering several handlers that way (much like event handlers in Java were).
I don't necessarily think exceptions are perfect either, just that Go's alternative seems like a step backward. But I'd actually quite like to be shown that I'm wrong about this.
[1] http://groups.google.com/group/golang-nuts/browse_thread/thread/1ce5cd050bb973e4/8bc45b58a32aed25?q=defer+panic&lnk=ol& http://groups.google.com/group/golang-nuts/browse_thread/thr...;
[2] http://blog.golang.org/2010/08/defer-panic-and-recover.html http://blog.golang.org/2010/08/defer-panic-and-recover.html