Ruby Error Handling, Beyond the Basics

An excerpt from, by Darko Gjorgjievski

Imagine you’re riding a bike. Now, imagine the designers of that bike built it so it rides smoothly only on roads without bumps and encountering one would result in the entire bicycle breaking! You wouldn’t want that, would you? Yet this is how thousands of software developers design their software every single day. They put error handling in as an afterthought, dealing with it only when it’s inevitable.

The truth is, it’s not their fault. Most of the material on this subject is very basic, covering simple things like raising an error, rescuing it, different error types and…that’s about it. This article will attempt to go deeper than that. I assume you’re familiar with the basics of error handling (using raise, begin/rescue, what StandardError is, error inheritance). That’s the only prerequisite for reading this article. Let’s begin.

What Did We Do Before Raising/Handling Exceptions?

Before exceptions were invented, the primary method of communication that something in the program has failed was through error return codes. As time passed, people looked at ways to clearly distinguish between what their program does and what would happen if it didn’t do what it was supposed to (return codes were far from ideal for this purpose) do. Thus, the invention of language constructs like:

  • raise
  • rescue
  • begin/end (Many other languages use different wording, like try/catch or throw, but the idea behind it remains the same.)

There are opposing views to using exceptions and error handling in the first place. Some of these points make sense and we’ll discuss them later in the article. For now, let’s get you familiar with some of the ways of handling errors in Ruby that can help you manage them better.

Continue reading this article on SitePoint

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.