0
0
Rubyprogramming~15 mins

Multiple rescue clauses in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Errors with Multiple Rescue Clauses in Ruby
📖 Scenario: Imagine you are writing a small program that divides numbers. Sometimes, the user might enter zero or a wrong input, causing errors. You want to handle these errors nicely so the program doesn't crash.
🎯 Goal: You will build a Ruby program that divides two numbers and uses multiple rescue clauses to handle different types of errors separately.
📋 What You'll Learn
Create two variables with exact values for numerator and denominator
Create a variable called result initialized to nil
Use a begin block to perform division
Add multiple rescue clauses to handle ZeroDivisionError and TypeError
Print the result or an error message
💡 Why This Matters
🌍 Real World
Handling errors gracefully is important in real programs to avoid crashes and give helpful messages to users.
💼 Career
Knowing how to use multiple rescue clauses helps you write robust Ruby code that can handle different problems clearly.
Progress0 / 4 steps
1
Set up numerator and denominator variables
Create a variable called numerator and set it to 10. Create another variable called denominator and set it to 0.
Ruby
Need a hint?

Use simple assignment like numerator = 10 and denominator = 0.

2
Initialize result variable
Create a variable called result and set it to nil.
Ruby
Need a hint?

Use result = nil to start with no value.

3
Add begin block with multiple rescue clauses
Write a begin block where you set result to numerator / denominator. Add two rescue clauses: one for ZeroDivisionError that sets result to the string "Cannot divide by zero", and one for TypeError that sets result to "Invalid types for division".
Ruby
Need a hint?

Use begin and rescue keywords to catch errors separately.

4
Print the result
Write puts result to display the value of result.
Ruby
Need a hint?

Use puts result to show the output.