繁体   English   中英

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

[英]Exception is only caught with `rescue` at the end of the line but not when using a `begin rescue` block

我的声明失败了:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM