只有在行尾使用`rescue`才能捕获异常,但在使用`begin rescue`块时则不会

时间:2013-04-24 17:37:04

标签: ruby exception rescue

我的陈述失败了:

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

1 个答案:

答案 0 :(得分:2)

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. "