【Ruby】Open-URIは例外を拾って404をチェックする

以下のコードでは、URLが404 Not Foundのときにエラーになって止まる。

require 'open-uri'
url = 'http://example.com'
html = open(url) do |f|
	f.read
end

URLを開けなかったら例外OpenURI::HTTPErrorを投げてくれるので、ちゃんと捕捉する。

require 'open-uri'
url = 'http://example.com'
begin
	html = open(url) do |f|
		f.read
	end
rescue OpenURI::HTTPError => e
	# 例外処理
end

これでオッケー。