Try, Go, Try!

Try, Go, Try!

Sergey Abbakumov

Some time ago, a new proposal has been appeared in the Go environment to introduce the built-in error checking try function (https://go.googlesource.com/proposal/+/master/design/32437-try-builtin.md) authored by Robert Griesemer.


This is to eliminate duplicate checks.

if err != nil {
  return nil, err
}

about which only the lazy did not speak.


By the way, this is not the first proposal to introduce new language constructs for error handling. There were already check and handle, which I already has written about (https://t.me/sea_plus_plus/77)


In a new proposal

f := try(os.Open(filename))


will be rewritten by the compiler to

f, err := os.Open(filename)
if err != nil {
    return nil, err
}

which is very convenient.


handle did not take root since it was very similar to the existing defer mechanism.


try will be implemented as a built-in function. Firstly, you cannot succeed in making it as a regular function, because you will need to be able to return from two stack frames at once. Secondly, the refusal to use the new keyword allows you to maintain backward compatibility with existing Go parsers.


By the way, C++, in my opinion, cannot also return from several stack frames at once. This problem can be solved, for example, using the non-standard GCC extension and macros: https://github.com/google/lmctfy/blob/master/util/errors.h#L229


So you can write

std::string s = RETURN_IF_ERROR(FunctionReturnsStatusOrString());

getting here pretty much everything the try gives in Go.


Telegram channel: https://t.me/sea_plus_plus

Report Page