On Wed, Dec 23, 2015 at 1:44 AM, gopanic <
kmak...@gmail.com> wrote:
>
> I'm new in golang. And this thing with defer recover() blows my mind. I
> still do not understand - why this behaviour is built into the language?
Because it seems like the best approach.
> I've found your(?) blog post
http://www.airs.com/blog/archives/376
> You wrote
>
>> Otherwise it would be difficult for a deferred function to call a
>> function which uses panic and recoverfor error handling; the recover might
>> pick up the panic for its caller, which would be confusing.
>
>
> So what? It's regular situation when something goes not like programmer
> expects, or when programmer makes mistakes.
The record function has to work one way or another. This way seems
good, for the reasons I stated. Why would it be better if recover
worked in some other way?
> I've spent few hours already trying to find answers for following questions:
>
> How it works internally?
The blog post you already found explains how it works in gccgo. In
gc, see runtime/panic.go. I'm happy to answer more specific
questions, but it's hard to answer a general one like this.
> Why programmer restricted to write func() { recover() } - is it design
> decision only? or maybe it caused by lang desing (f.i. it's very
> difficult/inefficient to implement support of defer recover())? - why defer
> recover() doesn't work at all (even with unwanted behavior)?
defer recover() works as documented. It doesn't do anything very
useful, but it works.
It's not a case that's worth worrying about, because a program that
uses defer func() { recover() }() is not a well written program. You
should never just discard an ongoing panic without even logging it.
There is no point to making the semantics of defer more complex in
order to make defer recover() act like defer func() { recover() }(),
since nobody should be writing either case anyhow.
> PS
> Somewhere I've read that reason is in backwards compatibility - is it so?
No. It was designed to work this way from the start. Since as far as
I know Go invented defer/recover, there is nothing to be backward
compatible with.
Ian