Handling Exceptions

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

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.