by troupo · 1y ago · 0 comments
They try to start, cannot do a specific operation, and they do an orderly shutdown. Or they should
Which is exactly what panic does.
Panic is a built-in function that stops the ordinary flow of control and begins panicking... The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes.
--- end quote ---
This is far from orderly. For example, what happens to other goroutines?
I also like how golang docs literally describe using panics as poor man's exceptions:
--- start quote ---
For a real-world example of panic and recover, see the json package from the Go standard library. It encodes an interface with a set of recursive functions. If an error occurs when traversing the value, panic is called to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value
...
The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values.
--- end quote ---
And I like how https://github.com/golang/go/issues/26799 describes that use of panic in the original version of this bog entry from 2010:
quote:
However, this is a poor example and a misuse of panic and recover as exceptions. See https://golang.org/doc/effective_go.html#panic
The example will be invalid soon with the release of go 1.11 as well. The panic/recover was removed from the unmarshal code. See master's
end quote.
The blog entry was later changed because this was fixed. It now refers to marshaling which, sadly, sill uses this mechanism.
The fact that this is still in the json package is a pain point, yes. Does it validate the use of panic as a form of flow control? No. Here is what "Effective Go" has to say about the topic:
https://go.dev/doc/effective_go#panic
quote:
But what if the error is unrecoverable? Sometimes the program simply cannot continue.
For this purpose, there is a built-in function panic that in effect creates a run-time error that will stop the program (but see the next section).
end quote.