0
0
Rubyprogramming~20 mins

Raise for throwing errors in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Raise Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code with raise?

Look at this Ruby code that uses raise. What will it print or return when run?

Ruby
def check_age(age)
  raise "Age must be positive" if age <= 0
  "Age is #{age}"
end

begin
  puts check_age(-1)
rescue => e
  puts e.message
end
AAge must be positive
BAge is -1
CRuntimeError: Age must be positive
DNo output
Attempts:
2 left
💡 Hint

Think about what raise does and how rescue catches errors.

🧠 Conceptual
intermediate
1:30remaining
Which statement about raise in Ruby is true?

Choose the correct statement about how raise works in Ruby.

A<code>raise</code> only works with <code>begin</code> blocks and nowhere else.
B<code>raise</code> stops the program immediately without any chance to handle the error.
C<code>raise</code> creates an error that can be caught by <code>rescue</code> blocks.
D<code>raise</code> automatically fixes the error it detects.
Attempts:
2 left
💡 Hint

Think about how Ruby handles errors and exceptions.

🔧 Debug
advanced
2:00remaining
Why does this Ruby code raise an error?

Look at this Ruby code. It raises an error. What is the cause?

Ruby
def divide(a, b)
  raise "Cannot divide by zero" if b == 0
  a / b
end

puts divide(10, 0)
ABecause the method is missing a return statement.
BBecause dividing by zero is not allowed and <code>raise</code> triggers the error.
CBecause <code>raise</code> is used incorrectly without an error class.
DBecause the method does not handle the error with <code>rescue</code>.
Attempts:
2 left
💡 Hint

Think about what happens when b is zero and how raise works.

📝 Syntax
advanced
1:30remaining
Which option correctly raises a custom error in Ruby?

Choose the correct Ruby code that raises a custom error with the message "Invalid input".

Araise "Invalid input"
Braise new ArgumentError("Invalid input")
Craise ArgumentError("Invalid input")
Draise ArgumentError, "Invalid input"
Attempts:
2 left
💡 Hint

Remember the syntax for raising errors with a specific error class and message.

🚀 Application
expert
2:30remaining
What is the output of this Ruby code with nested raise and rescue?

Analyze this Ruby code with nested raise and rescue. What will it print?

Ruby
def test
  begin
    raise "First error"
  rescue
    begin
      raise "Second error"
    rescue => e
      return e.message
    end
  end
end

puts test
ASecond error
BRuntimeError
CNo output
DFirst error
Attempts:
2 left
💡 Hint

Follow the flow of errors and rescue blocks carefully.