Ruby - Handle Division by Zero Exception

1. Introduction

Performing mathematical operations in any programming language comes with its challenges. In Ruby, one such challenge is the potential for dividing by zero. In this guide, we'll explore how to handle the ZeroDivisionError exception when trying to divide by zero.

A ZeroDivisionError is an exception raised in Ruby when attempting to divide a number by zero. This operation is mathematically undefined, and programming languages typically raise an error or exception when encountering it.

2. Program Steps

1. Define two numbers, the dividend, and the divisor.

2. Perform a division operation within a begin...rescue block.

3. If a ZeroDivisionError exception is encountered, handle it gracefully by displaying a custom error message.

4. If no exception is encountered, display the result of the division.

3. Code Program

# Define two numbers
numerator = 10
denominator = 0
# Perform the division operation within a begin...rescue block
begin
  result = numerator / denominator
  puts "The result of the division is #{result}."
rescue ZeroDivisionError
  puts "Error: Division by zero is not allowed!"
end

Output:

Error: Division by zero is not allowed!

Explanation:

1. numerator = 10 and denominator = 0: These lines define two numbers. In this example, the denominator is zero, which will trigger a ZeroDivisionError when dividing.

2. begin: This starts the begin...rescue block where we will attempt the division.

3. result = numerator / denominator: This line performs the division operation.

4. rescue ZeroDivisionError: This line catches the ZeroDivisionError exception if it is raised.

5. puts "Error: Division by zero is not allowed!": This line displays a custom error message if the ZeroDivisionError exception is encountered.


Comments