我试图理解Ruby中的异常,但我有点困惑.我使用的教程说,如果发生的异常与rescue语句识别的任何异常都不匹配,可以使用"else"来捕捉它:

begin  
# -  
rescue OneTypeOfException  
# -  
rescue AnotherTypeOfException  
# -  
else  
# Other exceptions
ensure
# Always will be executed
end

然而,我在后面的教程中也看到了"rescue"的用法,没有特别说明:

begin
    file = open("/unexistant_file")
    if file
         puts "File opened successfully"
    end
rescue
    file = STDIN
end
print file, "==", STDIN, "\n"

如果你能做到这一点,那么我还能用别的吗?或者我可以在最后使用通用的救援工具吗?

begin  
# -  
rescue OneTypeOfException  
# -  
rescue AnotherTypeOfException  
# -  
rescue
# Other exceptions
ensure
# Always will be executed
end

推荐答案

else表示块完成时没有抛出异常.无论块是否成功完成,ensure都会运行.例子:

begin
  puts "Hello, world!"
rescue
  puts "rescue"
else
  puts "else"
ensure
  puts "ensure"
end

这将打印Hello, world!,然后是else,然后是ensure.

Ruby相关问答推荐

Ruby错误-应为数组或字符串,已获取哈希

如何在 rspec 中使用 `eq` 匹配器和 `hash_include` 匹配器来获取哈希数组

有没有办法在 Capybara 中保持登录状态?

使用 RSpec 存根 Time.now

define_method:如何动态创建带参数的方法

Ruby |= 赋值运算符

在 Ubuntu 上安装 Ruby 1.9.1?

如何判断我是从 JRuby 还是 Ruby 运行?

无法在 macos-10.15.6 上Bundle 安装 puma 4.3.5 或 gem puma 与 ruby​​-2.6.6

如何使用 Ruby 2.3 中引入的 Array#dig 和 Hash#dig?

Jekyll - 找不到命令

为什么 Ruby 的 Date 类会自动加载,但 DateTime 不会?

Ruby 1.9:如何正确大写和小写多字节字符串?

Ruby - time.now UTC

Ruby Koans 的 test_sharing_hashes 中的附加问题的答案是什么?

Ruby - 无法修改冻结的字符串 (TypeError)

Ruby:是否可以在模块中定义类方法?

检索/列出 Redis 数据库中的所有键/值对

Ruby Activerecord IN 子句

Rubocop 25 线块大小和 RSpec 测试