Look at this Ruby code that uses raise. What will it print or return when run?
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
Think about what raise does and how rescue catches errors.
The raise command throws an error with the message "Age must be positive" because the age is -1. The rescue block catches this error and prints only the message, so the output is "Age must be positive".
raise in Ruby is true?Choose the correct statement about how raise works in Ruby.
Think about how Ruby handles errors and exceptions.
raise creates an exception that can be caught and handled by rescue blocks. It does not stop the program immediately if handled, and it does not fix errors automatically.
Look at this Ruby code. It raises an error. What is the cause?
def divide(a, b) raise "Cannot divide by zero" if b == 0 a / b end puts divide(10, 0)
Think about what happens when b is zero and how raise works.
The code raises an error because dividing by zero is not allowed. The raise command triggers a RuntimeError with the message "Cannot divide by zero" when b is zero.
Choose the correct Ruby code that raises a custom error with the message "Invalid input".
Remember the syntax for raising errors with a specific error class and message.
Option D uses the correct syntax: raise ArgumentError, "Invalid input". Option D raises a RuntimeError by default. Option D and D are syntax errors.
Analyze this Ruby code with nested raise and rescue. What will it print?
def test begin raise "First error" rescue begin raise "Second error" rescue => e return e.message end end end puts test
Follow the flow of errors and rescue blocks carefully.
The first raise triggers "First error" but it is rescued immediately. Inside that rescue, another raise triggers "Second error" which is rescued and its message is returned. So the output is "Second error".