Hacker News new | ask | show | jobs
by jitl 2932 days ago
Golang already has an exceptions-equivalent construct in the shape of panic() and recover(): https://blog.golang.org/defer-panic-and-recover

You’re free to write exception-full code using those constructs, although the community tends to use error return values for the most part.

2 comments

This is how I understood the use for panics:

https://stackoverflow.com/questions/44504354/should-i-use-pa...

    > You should assume that a panic will be immediately fatal, for 
    > the entire program, or at the very least for the current 
    > goroutine. Ask yourself "when this happens, should
    > the application immediately crash?" If yes, use a panic; 
    > otherwise, use an error.
In Java, say, exceptions are the standard for raising a normal error. A class of those exceptions are runtime errors which are equivalent of "panics". Yes you can handle them, but they denote a problem with the program that can't be solved by the interpreter (divide by zero error, etc)
If want (and if it makes sense) you can use panics as a control flow mechanism to quickly bubble up errors inside your implementations.

See an example in the standard library itself: https://golang.org/src/encoding/json/encode.go, line 295

What's frowned upon is leaking this out of your package's interface/contract.

Then it strikes me kind of like C++ exceptions. They have them, and it's kinda supported, and there are certain things you shouldn't do with them, so everyone just uses return codes.

Java/Python encourage the use of exceptions as returning error conditions, rather than return error codes.

panic() and recover() are not meant to be used like Java or C++ exceptions.
The phrase "are able to be" is more effectual than the phrase "are not meant to be" when it comes to how people use programming languages in the real world. If it's possible to build a Go system using only panic/recover and defer, just as it is using only interface{}, then there's some people who will use them that way.