What is the difference between throw/catch and raise/rescue ?
What is the difference between throw/catch and raise/rescue ?
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 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.
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.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.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.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 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.
raise
is used to generate an exception when an error occurs. rescue
is used to catch and determine how to handle these exceptions.raise
is used to throw an exception, and rescue
is used to catch this exception and handle it.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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào