哪些情况需要投掷/接住长生不老药? [英] Which Situations Require Throw/Catch In Elixir?

查看:87
本文介绍了哪些情况需要投掷/接住长生不老药?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,围绕这个 Elixir文档的页面


在Elixir中,可以抛出一个值,以后再捕获它。 throw and catch
保留用于除非使用throw and catch否则无法检索
值的情况。

In Elixir, a value can be thrown and later be caught. throw and catch are reserved for situations where it is not possible to retrieve a value unless by using throw and catch.

这些情况相当在实践中不常见,除非
与未提供适当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.

这篇关于哪些情况需要投掷/接住长生不老药?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆