In most other languages, the catch and throw statements do what the begin, rescue, and raise statements do in Ruby. I know the you can do this with these two statements:
catch :done do puts "I'm done." end
and
if some_condition throw :done end
But what is this useful for? Can somebody please give me an example of what catch and throw statements are used for in Ruby?
Answer: The “throws” keyword is used to declare the exception with the method signature. The throw keyword is used to explicitly throw the exception. The try-catch block is used to handle the exceptions thrown by others.
Re-throwing exceptions When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects).
From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method.
Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.
You can use this to break out of nested loops.
INFINITY = 1.0 / 0.0 catch (:done) do 1.upto(INFINITY) do |i| 1.upto(INFINITY) do |j| if some_condition throw :done end end end end
If you had used a break statement above, it would have broken out of the inner loop. But if you want to break out of the nested loop, then this catch/throw would be really helpful. I have used it here to solve one of the Euler problems.
I have been looking for a good example for a while, until I met Sinatra. IMHO, Sinatra exposes a very interesting example usage for catch
.
In Sinatra you can immediately terminate a request at any time using halt
.
halt
You can also specify the status when halting...
halt 410
Or the body...
halt 'this will be the body'
Or both...
halt 401, 'go away!'
The halt method is implemented using throw.
def halt(*response) response = response.first if response.length == 1 throw :halt, response end
and caught by the invoke
method.
There are several uses of :halt
in Sinatra. You can read the source code for more examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With