多级返回的恐慌

huangapple go评论78阅读模式
英文:

panic for multilevel returns

问题

有没有更好的方法来从长序列的递归函数调用中返回?
我目前使用类似这样的标记值来引发panic:

type exitNow int
...
panic(exitnow(0))

以一次返回多个级别。在根函数中,调用recover进行一般错误处理(将panic转换为错误)并将exitNow作为特殊情况处理。

这个方法很好用,我只是想知道是否有更好的方法。

我已经使用了一个bool类型的返回值来实现相关的目的,但是再使用一个来处理这个问题会很麻烦(每个函数的每次调用都需要一个if语句)。

如果有帮助的话,这是递归下降解析器的实现的一部分。

英文:

Is there a better way to return from long sequences of recursive function calls?
I currently panic with a marker value like this:

type exitNow int
...
panic(exitnow(0))

to return multiple levels at once. At the root function a call to recover does general error handling (turning panics into errors) and handles exitNow as a special case.

This works fine I just want to know if there is a better way.

I already use a bool return value for a related purpose but using another one for this would be a pain. (every call to every function would need an if statment)

If it helps any this is part of the implimentation of a recusive decent parser.

答案1

得分: 3

我在我的解析器中也使用这种方法。不过,我不会因为整数值而恐慌。我使用实际的当前错误作为恐慌消息。调用recover()的顶层函数只是附加一些文件/行/列信息,然后将其作为常规的error返回。

这种方法和从所有函数中返回错误是Go中唯一的方法。对于解析器的情况来说,恐慌方法更加有效,因为它使得词法分析规则的实现(和阅读)变得更简单,因为没有到处都是if err != nil { return }的部分。

英文:

I use this approach myself in my parsers. I don't panic with an integer value though. I use the actual current error as the panic message. The top level call doing the recover() simply appends some file/line/column information and then returns it as a regular error.

This method, and just returning errors from all functions are the only ways to do this in Go. The panic approach is a great deal more effective for the parser case, as it makes the lexer rules considerably simpler to implement (and read) as there are no if err != nil { return } parts littered everywhere.

huangapple
  • 本文由 发表于 2012年12月1日 01:52:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/13650493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定