Câu hỏi phỏng vấn Ruby
Câu hỏi

What is the difference between throw/catch and raise/rescue ?

Câu trả lời

In programming, particularly in languages like Ruby and Java, the concepts of throw/catch and raise/rescue are fundamental to handling exceptions and controlling program flow. These mechanisms serve different purposes and are used in different contexts.

Throw and Catch

Throw and catch mechanisms are primarily used for controlling program flow rather than handling errors or exceptions. When you throw, you are effectively signaling an event that may not necessarily be an error condition but requires exiting from a nested loop or bypassing certain sections of code. The catch block is where the program flow is transferred after a throw is executed.

  • Usage: throw is used to exit from deeply nested loops or to skip over sections of code when a specific condition is met. It is not typically used for error handling.
  • Control Flow: When throw is executed, it immediately terminates the execution of the current block of code and transfers control to the nearest catch block that matches the thrown symbol.
  • Example: In Ruby, you might use throw and catch to break out of a complex series of nested loops or conditionals when a specific condition is met that does not necessarily represent an error.
ruby Copy
result = catch(:done) do
  for i in 0..100
    for j in 0..100
      throw :done, i*j if i*j > 50
    end
  end
end
puts result  # This would print the first product over 50.

Raise and Rescue

Raise and rescue are used for actual error handling. When an error occurs, you raise an exception. This exception is then caught by a rescue block where you define how to handle the error.

  • Usage: raise is used to generate an exception when an error occurs. rescue is used to catch and determine how to handle these exceptions.
  • Error Handling: This mechanism is specifically designed for dealing with errors in your application. It allows the program to handle exceptions gracefully without crashing.
  • Example: In Ruby, raise is used to throw an exception, and rescue is used to catch this exception and handle it.
ruby Copy
def divide(a, b)
  raise "Division by zero error" if b == 0
  a / b
rescue => e
  puts e.message
end

puts divide(10, 0)  # Outputs "Divisi...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

Are class variables inherited?

middle

What does self mean?

entry

Is everything in Ruby an object?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào