Exception handling in Google Go language [closed]

panic/recover is moral equivalent of try/catch exceptions. There is superficial difference (syntax) and a subtle, but important, difference of intended use.

The best explanations of problems with exceptions in general is “Cleaner, more elegant, wrong” and that’s a good overview of pros/cons of exceptions vs. returning error codes.

Go designers decided that error handling by returning error codes from functions is the idiomatic Go way and the language supports multiple return values to make it syntactically easy. While panic/recover is provided, the difference is not of functionality but intended use.

Other languages exposing exceptions promote their use and in practice they are used frequently (sometimes even misused).

Go discourages the use of panic/recover. You can do it but you’re only supposed to do it in very limited scenarios.

If you look at Go’s own standard library, most uses of panic are for signaling fatal errors, indicating either an internal error (i.e. bug) in the library code or calling the library with wrong data (e.g. passing non-json data to json decoding functions).

But as the article you linked to points out: “The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values.”

This is different from languages like C#, Java, Python or C++, where a lot of standard library code can throw exceptions to signal errors. Those languages want you to use exceptions. Go discourages the use of panic/recover.

To summarize:

  • idiomatic Go style is to use error codes to tell the caller about errors
  • use panic/recover only in rare cases:
    • to “crash” your program when encountering internal inconsistency indicating bugs in your code. It’s basically a debugging aid.
    • if it dramatically simplifies error handling in your code (but if the code is to be used by others, never expose such panics to callers)

In practice the important thing is to use language’s idiomatic style. In Go that’s returning error codes and avoiding panic/recover. In C# that’s using exceptions to signal some of the errors.

Leave a Comment

tech