Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the syntax (=>) used in assign error object to variable of `rescue` method?

The rescue which could assigns a variable to reference the error object has this syntax (=>)

rescue => e

If rescue is the one of the general method call, what's the meaning of =>. Could I use the same syntax on other method call?

my_method arg1, arg2 => my_obj
like image 309
steveyang Avatar asked Mar 13 '12 15:03

steveyang


People also ask

How to rescue exception Ruby?

In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from. Note: When using raise without specifying an exception class, Ruby will default to RuntimeError .

How does rescue work in Ruby?

The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.

What is begin rescue in Ruby?

Similar to PHP's try-catch, Ruby's exception handling begins with the begin-rescue block. In a nutshell, the begin-rescue is a code block that can be used to deal with raised exceptions without interrupting program execution.

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .


1 Answers

While raise is indeed a method, rescue is not. It is a keyword and defined on parse.y:10467. As such, the syntax you have is special to rescue (since => e isn't any sort of method argument), and not valid for methods themselves (at least not with the same meaning). How/where the rescue => e syntax itself is defined in the parser I'm not entirely sure.

like image 199
Andrew Marshall Avatar answered Sep 21 '22 07:09

Andrew Marshall