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