Ruby Exception Handling

Ruby Exception Handling: ZeroDivisionError

Today in our continued journey through our Ruby Exception Handling series we’ll be taking a closer look at the ZeroDivionError. As you may suspect the ZeroDivisionError occurs when attempting to divide a number by zero.

In this article we’ll briefly explore the ZeroDivisionError in more detail, including where it sits within the Ruby Exception class hierarchy and showing a few simple code examples to illustrate how ZeroDivisionErrors occur in the first place. Let’s get started!

The Technical Rundown

  • All Ruby exceptions are descendants of the Exception class, or a subclass therein.
  • StandardError is a direct descendant of the Exception class, and is also a superclass with many descendants of its own.
  • ZeroDivisionError is the direct descendant of StandardError.

When Should You Use It?

Producing a ZeroDivisionError is quite simple, but there are a few small quirks that you’ll want to be aware of before assuming your rescue ZeroDivisionError => e statement will always catch attempts to divide by zero-ish values. To illustrate we have a few example methods showing normal division, division by exactly zero, division by floating zero, and division by negative floating zero. As usual we’ll start with the full code snippet and then we’ll briefly go through it to see what’s going on:

We start with a normal and functional #division_example method:

This works as expected and outputs a result of 3. However, if we change our denominator to 0 we’ll produce a ZeroDivisionError, as seen in #zero_division_example:

That should make sense to most of us I think: Just like when you were bored in school and were messing around with your calculator and tried dividing by zero you’d get an error, the same applies in Ruby (and probably all other programming languages for that matter). However, dividing by zero in all cases may not work exactly as you’d think. Watch what happens when we change our denominator from 0 to a floating point representation of 0.0:

Suddenly we no longer produce a ZeroDivisionError but, instead, we get an output of Infinity. This is because Ruby handles various numeric data object types differently: whole numbers or Integers like 0 are calculated differently than Floats like 0.0.

We can see this strangeness continue if we change the denominator from 0.0 to the negative version of -0.0, which produces an output of negative Infinity:

To get the most out of your own applications and to fully manage any and all Ruby Exceptions, check out the Airbrake Ruby exception handling tool, offering real-time alerts and instantaneous insight into what went wrong with your Ruby code, including integrated support for a variety of popular Ruby gems and frameworks.