doutongfu9484 2009-12-05 13:19
浏览 72
已采纳

Google的“ Go”语言多值返回语句是否可以替代异常?

It seems to me Google's alternatives to exceptions are

  • GO: multi-value return "return val, err;"
  • GO, C++: nil checks (early return)
  • GO, C++: "handle the damn error" (my term)
  • C++: assert(expression)

  • GO: defer/panic/recover are language features added after this question was asked

Is multi-value return useful enough to act as an alternative? Why are "asserts" considered alternatives? Does Google think it O.K. if a program halts if an error occurs that is not handled correctly?

Effective GO: Multiple return values

One of Go's unusual features is that functions and methods can return multiple values. This can be used to improve on a couple of clumsy idioms in C programs: in-band error returns (such as -1 for EOF) and modifying an argument.

In C, a write error is signaled by a negative count with the error code secreted away in a volatile location. In Go, Write can return a count and an error: “Yes, you wrote some bytes but not all of them because you filled the device”. The signature of *File.Write in package os is:

func (file *File) Write(b []byte) (n int, err Error)

and as the documentation says, it returns the number of bytes written and a non-nil Error when n != len(b). This is a common style; see the section on error handling for more examples.

Effective GO: Named result parameters

The return or result "parameters" of a Go function can be given names and used as regular variables, just like the incoming parameters. When named, they are initialized to the zero values for their types when the function begins; if the function executes a return statement with no arguments, the current values of the result parameters are used as the returned values.

The names are not mandatory but they can make code shorter and clearer: they're documentation. If we name the results of nextInt it becomes obvious which returned int is which.

func nextInt(b []byte, pos int) (value, nextPos int) {

Because named results are initialized and tied to an unadorned return, they can simplify as well as clarify. Here's a version of io.ReadFull that uses them well:

func ReadFull(r Reader, buf []byte) (n int, err os.Error) {
  for len(buf) > 0 && err == nil {
    var nr int;
    nr, err = r.Read(buf);
    n += nr;
    buf = buf[nr:len(buf)];
  }
  return;
}

Why does Go not have exceptions?

Exceptions are a similar story. A number of designs for exceptions have been proposed but each adds significant complexity to the language and run-time. By their very nature, exceptions span functions and perhaps even goroutines; they have wide-ranging implications. There is also concern about the effect they would have on the libraries. They are, by definition, exceptional yet experience with other languages that support them show they have profound effect on library and interface specification. It would be nice to find a design that allows them to be truly exceptional without encouraging common errors to turn into special control flow that requires every programmer to compensate.

Like generics, exceptions remain an open issue.

Google C++ Style Guide: Exceptions

Decision:

On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.

Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.

Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch.

GO: Defer, Panic and Recover

Defer statements allow us to think about closing each file right after opening it, guaranteeing that, regardless of the number of return statements in the function, the files will be closed.

The behavior of defer statements is straightforward and predictable. There are three simple rules:

1. A deferred function's arguments are evaluated when the defer statement is evaluated.

In this example, the expression "i" is evaluated when the Println call is deferred. The deferred call will print "0" after the function returns.

    func a() {
         i := 0
         defer fmt.Println(i)
         i++
         return    
    }

2. Deferred function calls are executed in Last In First Out order after the surrounding function returns. This function prints "3210":

     func b() {
        for i := 0; i < 4; i++ {
            defer fmt.Print(i)
        }   
     }

3. Deferred functions may read and assign to the returning function's named return values.

In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function returns 2:

    func c() (i int) {
        defer func() { i++ }()
        return 1 
    }

This is convenient for modifying the error return value of a function; we will see an example of this shortly.

Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses.

Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.

Here's an example program that demonstrates the mechanics of panic and defer:

<snip>

For a real-world example of panic and recover, see the json package from the Go standard library. It decodes JSON-encoded data with a set of recursive functions. When malformed JSON is encountered, the parser calls panic is to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value (see the 'error' and 'unmarshal' functions in decode.go). There is a similar example of this technique in the Compile routine of the regexp package. The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values.

Other uses of defer (beyond the file.Close() example given earlier) include releasing a mutex:

mu.Lock()  
defer mu.Unlock
  • 写回答

7条回答 默认 最新

  • dqyin0101 2009-12-05 13:30
    关注

    Multiple returns are not unique to Go, and they're not a substitute for exceptions. In C (or C++) terms, they are a concise and user-friendly substitute for returning a struct (object) containing multiple values.

    They do provide a convenient means of indicating errors, if that's all you mean.

    Why are "asserts" considered alternatives?

    Asserts are initially for debugging. They halt the program in situations where it is in an "impossible" state, one that the design says should not happen, but which has anyway. Returning an error is unlikely to help much. The code base obviously doesn't work yet, so how on earth can it successfully recover? Why would you even want it to, when there's a bug that needs attention?

    Using asserts in production code is a bit of a different matter - obviously there are performance and code size concerns, so the usual approach is to remove them once your code analysis and tests have convinced you that the "impossible" situations really are impossible. But, if you're running code at this level of paranoia, that it's auditing itself, then you're probably also paranoid that if you let it carry on running in an "impossible" state, then it might do something dangerously broken: corrupting valuable data, overrunning a stack allocation and perhaps creating security vulnerabilities. So again, you just want to shut down as soon as possible.

    The stuff you use asserts for really isn't the same as the stuff you use exceptions for: when programming languages like C++ and Java provide exceptions for "impossible" situations (logic_error, ArrayOutOfBoundsException), they unintentionally encourage some programmers to think that their programs should attempt to recover from situations where really they're out of control. Sometimes that is appropriate, but the Java advice not to catch RuntimeExceptions is there for a good reason. Very occasionally it's a good idea to catch one, which is why they exist. Almost always it's not a good idea to catch them, meaning that they amount to halting the program (or at least the thread) anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?