0
0
Rubyprogramming~15 mins

Why error handling uses rescue in Ruby - See It in Action

Choose your learning style9 modes available
Why error handling uses rescue
📖 Scenario: Imagine you are writing a small program that divides two numbers. Sometimes, the second number might be zero, which causes an error. You want to handle this error gracefully so the program doesn't crash.
🎯 Goal: You will learn how to use rescue in Ruby to catch errors and handle them safely.
📋 What You'll Learn
Create two variables with exact values
Add a variable to hold the result
Use begin and rescue to handle division errors
Print the result or an error message
💡 Why This Matters
🌍 Real World
Error handling is important in real programs to avoid crashes and provide helpful messages to users.
💼 Career
Knowing how to use <code>rescue</code> in Ruby is essential for writing reliable and user-friendly applications.
Progress0 / 4 steps
1
Create two variables for numbers
Create two variables called num1 and num2 with values 10 and 0 respectively.
Ruby
Need a hint?

Use = to assign values to variables.

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

Use result = nil to start with no value.

3
Use begin and rescue to handle division
Write a begin block where you divide num1 by num2 and assign it to result. Use rescue ZeroDivisionError to catch division by zero errors and set result to the string "Cannot divide by zero".
Ruby
Need a hint?

Use begin and rescue ZeroDivisionError to catch errors.

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

Use puts result to show the output.