January 2024
Intermediate to advanced
718 pages
20h 15m
English
Here’s some simple code that uses the open-uri library to download the contents of a web page and write it to a file, line by line:
| | require "open-uri" |
| | URI.open("https://pragprog.com/news/index.html") do |web_page| |
| | output = File.open("index.html", "w") |
| | while (line = web_page.gets) |
| | output.puts line |
| | end |
| | output.close |
| | end |
What happens if we get a fatal error halfway through? We certainly don’t want to store an incomplete page to the output file.
Let’s add some exception-handling code and see how it helps. To start exception handling, we enclose the code that could raise an exception in a begin/end block and use one or more rescue clauses to tell Ruby ...
Read now
Unlock full access