Here is my ruby program
require 'net/http'
require 'uri'
begin
    url = URI.parse("http://google.com")
rescue Exception => err
    p err
    exit
end
http = Net::HTTP.new(url.host, url.port) 
res = http.head("/")
p res.code
It works fine, however if I remove http:// from URL.parse(), It gives me this error:
/usr/lib/ruby/1.9.1/net/http.rb:1196:in `addr_port': undefined method `+' for nil:NilClass (NoMethodError) ...
from /usr/lib/ruby/1.9.1/net/http.rb:1094:in `request'
from /usr/lib/ruby/1.9.1/net/http.rb:860:in `head'
Is it the correct way to handle Exception ?
I know maybe the URL is not correct, but It should raise an exception URI::InvalidURIError instead of accepting and continue the program ?
If you say u = URI.parse('http://google.com'), you'll get a URI::HTTP back and the u.port will have a default of 80. If you say u = URI.parse('google.com'), you'll get a URI::Generic back with the u.port will be nil as will u.host.
So, when you do this:
url  = URI.parse('google.com')
http = Net::HTTP.new(url.host, url.port)
You're really doing this:
http = Net::HTTP.new(nil, nil)
and Net::HTTP doesn't like that very much at all. You could try something like this instead:
if(str.to_s.empty?)
    # complain loudly about a missing str
end
begin
    url = URI.parse(str)
    url = URI.parse('http://' + str) if !url.scheme
    if(url.scheme != 'http' && url.scheme != 'https')
        # more complaining about bad input
    end
    http = Net::HTTP.new(url.host, url.port)
    #...
rescue URI::Error => e
    # even yet more complaining
end
That sort of thing should bypass the exception completely and cover a few other things that you might be interested in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With