Skip to content

Comment on Toward Go 1.3parent

Comments

You can abuse "panic" to implement exceptions in Golang the way you can abuse "longjmp" to do that in C. The purpose of "panic" isn't for general-purpose exceptions. It's to panic the program.

Note that this mechanic is used in the golang standard library and works great as a catchall: http://golang.org/src/pkg/text/template/exec.go#L93

It's clear you shouldn't throw.

But correct code must assume that any function you call might throw; which is why you should use defer blocks e.g. to release resources, instead of C-style "cleanup at the bottom of the function". (Defer is also prettier IMHO)

It's idiomatically correct to ignore panics and let them take the whole program down with a crash. A panic indicates that your program is already doing extremely incorrect things. Rare is the program where picking itself up and continuing a possible Sorcerer's Apprentice mode rampage is better than just stopping and telling you what needs fixing.

You're not "throwing". You're "panicking".

Or raising? That's just terminology. The behaviors of c++/java/python exceptions and Go panics are similar regardless of the name the keyword has in those language:

The execution is suspended, the stack unwound until the first handler, the handler has access to a value that is "thrown". Stack information is preserved in order to print meaningful stack traces.

C++/java/python have syntax sugar that performs a pattern match on the thrown object to decide whether to handle it or bubble it up, while in Go you do it manually, but other that that I don't see much of a difference in the mechanics of them to justify being so pedantic about the naming of the action.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.