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

StackOverflow https://stackoverflow.com/questions/16198644

  •  11-04-2022
  •  | 
  •  

Question

I have a statement that fails:

result = service.load_data()

Now the following suppresses the error and I can then check for nil

result = service.load_data() rescue nil

But when I do the following the initial error is thrown right up to the UI and I don't get the details of the exception.

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

I am sure there is a silly detail I must be missing but I can't seem to spot the problem here. So why isn't the rescue block invoked?

Update: The error I got was this:

getaddrinfo: nodename nor servname provided, or not known
Was it helpful?

Solution

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

use the above.

tried to replicate the error here as below:

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)

Fixed it as below:

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. "
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top