0
0
Rubyprogramming~15 mins

Begin/rescue/end blocks in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Errors with Begin/Rescue/End Blocks in Ruby
📖 Scenario: Imagine you are writing a small program that divides numbers. Sometimes, the user might enter zero as the divisor, which causes an error. We want to handle this error gracefully so the program doesn't crash.
🎯 Goal: You will build a Ruby program that safely divides two numbers using begin, rescue, and end blocks to catch division errors and print a friendly message.
📋 What You'll Learn
Create two variables with exact values for dividend and divisor
Create a variable to hold the result initialized to nil
Use a begin/rescue/end block to perform division and catch ZeroDivisionError
Print the result or an error message
💡 Why This Matters
🌍 Real World
Handling errors like division by zero is common in programs that do math or process user input. This prevents crashes and improves user experience.
💼 Career
Understanding error handling with begin/rescue/end blocks is essential for writing robust Ruby applications, a key skill for Ruby developers.
Progress0 / 4 steps
1
Set up dividend and divisor variables
Create two variables called dividend and divisor with the exact values 10 and 0 respectively.
Ruby
Need a hint?

Use simple assignment like dividend = 10 and divisor = 0.

2
Create a 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
Use begin/rescue/end to divide safely
Write a begin block where you set result to dividend / divisor. Add a rescue ZeroDivisionError block that sets result to the string "Cannot divide by zero". Close the block with end.
Ruby
Need a hint?

Use begin and end to wrap the division. Rescue ZeroDivisionError to handle division by zero.

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

Use puts result to show the output.