问题描述
因此,围绕这个。
这些情况相当在实践中不常见,除非
与未提供适当API的库接口。
Those situations are quite uncommon in practice except when interfacing with libraries that do not provide a proper API.
在某些情况下需要使用 try / throw / catch
与 try / rescue
?这是为了与一些现有的Erlang库接口吗?页面上的示例显示了Elixir代码,这让我感到有些困惑。
Which situations would require using try/throw/catch
vs. try/rescue
? Is this for interfacing with some existing Erlang libraries? The sample on the page shows Elixir code which is what I find a bit confusing.
我应该寻找的适当的API是什么?我的意思是这将是一个协议吗?
What would be the "proper API" that I should be looking for? I mean would this be a protocol?
推荐答案
我认为raise / rescue与异常处理有关,这完全是意料之外的情况,其中您想拥有一个堆栈跟踪,并由一个程序员来查看它。发生这种情况的原因可能是多种原因-程序员错误,错误的环境等,但用户提供无效数据并不是其中一种情况。
I consider raise/rescue to be explicitly about exception handling - meaning completely unexpected situation where you want to have a stacktrace and a programmer looking at it. It may happen because of multiple things - programmer error, wrong environment, etc, but user providing invalid data is not one of those cases.
在某些地方抛出/捕获很有用发生了预期的故障,但是您仍想使用升高/救援提供的非本地控制流。这也使您可以省去有时有时相当可观的构建堆栈跟踪的成本。经典示例如下:
Throw/catch is useful in places where you have expected failures, but you still want to use the non-local control flow that is offered by raise/rescue. This also allows you to skip the cost of building a stacktrace that is sometimes considerable. Classic examples are:
- 退出深度嵌套的递归调用:
- 正常的错误处理过于昂贵(可能发生在太多地方):
- 您有一个非本地构造(例如交易):
- exiting a deeply nested recursive call: https://github.com/devinus/poison/blob/master/lib/poison/parser.ex#L34-L46
- normal error handling is too expensive (can occur in too many places): https://github.com/michalmuskala/mongodb_ecto/blob/master/lib/mongo_ecto/objectid.ex#L29-L43
- you have an non-local construct (like transactions): https://github.com/elixir-lang/ecto/blob/428126157b1970d10f9d5233397f07c35ce69cac/test/support/test_repo.exs#L84-L98
我选择一个而不是另一个的经验法则是捕获对于正常运行程序至关重要,而在一般情况下应可移动救援。当然,该规则也有例外,但我认为这是有用的第一级区别。
My rule of thumb for choice of one over the other would be that catch is essential to properly functioning program while rescue should be removable in the general case. Of course there are exceptions to that rule, but I think it's a useful first-level distinction.
这篇关于哪些情况需要投掷/接住长生不老药?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!