Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is catch and throw used for in Ruby?

Tags:

ruby

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?

like image 862
ab217 Avatar asked Sep 15 '10 10:09

ab217


People also ask

What is the use of catch and throw?

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.

What does throw in catch block do?

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).

Is it better to use throws or try catch?

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.

What is the difference between throw and catch?

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.


2 Answers

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.

like image 57
bragboy Avatar answered Sep 26 '22 10:09

bragboy


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.

like image 31
Simone Carletti Avatar answered Sep 23 '22 10:09

Simone Carletti