如何在没有开始和结束块的情况下在 Ruby 中使用救援
我知道有一个 begin
如何单独使用 rescue
块?
它是如何工作的?它如何知道哪些代码正在被监视?
I know of the standard technique of having a begin <some code> rescue <rescue code> end
How does one just use the rescue
block on its own?
How does it work, and how does it know which code is being monitored?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
方法“def”可以充当“begin”语句:
A method "def" can serve as a "begin" statement:
您还可以内联救援:
将打印出“异常!”因为“字符串不能被强制转换为 Fixnum”
You can also rescue inline:
will print out "EXCEPTION!" since 'String can't be coerced into Fixnum'
我在 ActiveRecord 验证中经常使用 def/rescue 组合:
我认为这是非常精简的代码!
I'm using the def / rescue combination a lot with ActiveRecord validations:
I think this is very lean code!
示例:
此处,
def
作为begin
语句:Example:
Here,
def
as abegin
statement:奖金!您也可以使用其他类型的块来执行此操作。例如:
在 irb 中输出:
Bonus! You can also do this with other sorts of blocks. E.g.:
Outputs this in
irb
: