【问题标题】:Exception is only caught with `rescue` at the end of the line but not when using a `begin rescue` block异常仅在行尾使用 `rescue` 捕获,但在使用 `begin rescue` 块时不会捕获
【发布时间】:2013-04-24 17:37:03
【问题描述】:

我有一个失败的声明:

result = service.load_data()

现在下面会抑制错误,然后我可以检查nil

result = service.load_data() rescue nil

但是当我执行以下操作时,初始错误会直接被抛出到 UI 并且我没有得到异常的 details

begin
   result = service.load_data()
rescue => details         
   logger.fatal "Failed to load the data: #{details}"
end

我确信我一定遗漏了一个愚蠢的细节,但我似乎无法在这里发现问题。那么为什么不调用 rescue 块呢?

更新:我得到的错误是这样的:

getaddrinfo: nodename nor servname provided, or not known

【问题讨论】:

  • 发生什么样的错误?
  • @SergioTulentsev getaddrinfo: nodename nor servname provided, or not known(我更新了我的答案)
  • 检查'rescue'的拼写(你的帖子有'resuce')。
  • 你还没有提供异常类,但是对于任何想要帮助的人来说,它可能是SocketError
  • 另外,使用不带类的rescue 将默认为StandardError,如果您的异常类不继承自该类,它将失败。您可能需要rescue Exception 或更具体地指定类。也就是说,如果是 /is/ SocketError,则继承自 StandardError,因此您的代码应该按原样工作

标签: ruby exception rescue


【解决方案1】:
begin
   result = service.load_data()
rescue AnExceptionKlass => details    # here the name is SocketError    
   logger.fatal "Failed to load the data: #{details}"
end

使用上面的。

尝试在此处复制错误如下:

require 'net/http'
Net::HTTP.start('http://www.google.com') do |http|
response = http.get('/')
puts response
end
#=> getaddrinfo: No such host is known.  (SocketError)

修复如下:

require 'net/http'

begin

  htt = Net::HTTP.start('http://www.google.com')
  response = htt.get('/')
  puts response

rescue SocketError => details    # or the Exception class name may be SocketError    
   p "Failed to load the data: #{details}"
end

#=> "Failed to load the data: getaddrinfo: No such host is known. "

【讨论】:

  • 永远不要rescue Exception => e 甚至不要将其作为“示例”。 stackoverflow.com/questions/10048173/…
  • @nitsujri 您是否完整阅读了答案?你看过我给的cmets吗?加油!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多