Title photo
frugal technology, simple living and guerrilla large-appliance repair

Regular blog here, 'microblog' there

Many of my traditional blog post live on this site, but a great majority of my social-style posts can be found on my much-busier microbloging site at updates.passthejoe.net. It's busier because my BlogPoster "microblogging" script generates short, Twitter-style posts from the Linux or Windows (or anywhere you can run Ruby with too many Gems) command line, uploads them to the web server and send them out on my Twitter and Mastodon feeds.

I used to post to this blog via scripts and Unix/Linux utilities (curl and Unison) that helped me mirror the files locally and on the server. Since this site recently moved hosts, none of that is set up. I'm just using SFTP and SSH to write posts and manage the site.

Disqus comments are not live just yet because I'm not sure about what I'm going to do for the domain on this site. I'll probably restore the old domain at first just to have some continuity, but for now I like using the "free" domain from this site's new host, NearlyFreeSpeech.net.

Sat, 13 Jan 2018

Handling potential errors in Ruby with begin/rescue/else

I have a couple of points in my BlogPoster Ruby script where an error can cause the program to end, and I have been at odds as to how to deal with it.

I had been looking at the various Ruby Gems that I am using for tips on how they might handle errors more gracefully and didn't gain any insight.

Turns out I was looking in the wrong place.

Today I took a few minutes to search for how Ruby handles errors and exceptions, and I found the begin ... rescue ... else methods. The Bastards Book of Ruby explains them very well.

I quickly wrote this little program to make sure it worked (it does). Though I'm in the middle of a method-based rewrite of the BlogPoster program, I might hack this into the old script to see if I can keep the program from stopping when the Nokogiri and Twitter Gems encounter problems (the former with unresolvable URLs, the latter with connectivity issues).

Here is my "test" of `begin ... rescue ... else:

#!/usr/bin/env ruby

# Handling potential errors in Ruby with begin/rescue/else
# The 'error' here is trying to divide by zero.

    puts "The expression 1/0 doesn\'t work"
    puts "The expression 1/0 does work"

    puts "The expression 1/1 doesn\'t work"
    puts "The expression 1/1 does work"

# Expected output:
# The expression 1/0 doesn't work
# The expression 1/1 does work

Update: I tried this with "real" code, and it works!