Feature #12623
closed
rescue in blocks without begin/end
Added by Nondv (Dmitry Non) over 8 years ago.
Updated almost 3 years ago.
Description
Hi there!
There's pretty nice feature that we can use "short rescue" in method definitions:
def my_method
raise '1234'
rescue
puts 'rescued'
end
What about using this in blocks?
loop do
n = enumerator.next
# do something
rescue StopIteration
end
P.S. actually I am not sure if this FR was not created earlier but I couldn't google it.
P.P.S sorry for my english
- Description updated (diff)
+1, I often want this and never understood why it only worked with methods.
- Description updated (diff)
AFAIK, it has been proposed a few times.
An objection is that rescue
in {}
block feels weird.
An objection is that rescue in {} block feels weird.
Do you mean in one-line or multi-line form?
Multiline:
list.each { |x|
# do something
rescue
# do something
}
In single-line there's ambiguous case:
# not implemented
list.each { |x| action_1; action_2; rescue; 'error!' }
# this is valid
list.each { |x| action_1; action_2 rescue 'error!' }
But 2nd line looks bad anyway :(
So, what's problem of "feels weird"?
IMHO there're not many people that will use it like that (my first example in single-line).
Dmitriy Non wrote:
list.each { |x|
# do something
rescue
# do something
}
-1. This is odd. I cannot remember any other language syntax that goes likes this. Java, C++, C# and all other language that use {} as block notations share this syntax to write exception handlings:
static void Main()
{
try
{
// something
}
catch (Exception e)
{
// something
}
finally
{
// something
}
}
I cannot remember any other language syntax
So, case statement in Ruby is different too.
+ it is not necessary to use this.
BTW AFAIK ruby-style-guide banned multiline {}
Nobuyoshi Nakada wrote:
An objection is that rescue
in {}
block feels weird.
I feel the same way. I think it feels weird because in Ruby, program structures starting with a keyword (if
/while
/do
/def
/...) can contain keywords (else
, rescue
,...) and end with keywords (end
), but symbols ({}
, []
,...) and keywords are not mixed.
This, combined with the fact that {}
is mostly used single-line, may suggest that adding rescue
to do
blocks might work, but not for {}
blocks.
- Is duplicate of Feature #7882: Allow rescue/else/ensure in do..end added
- Status changed from Open to Closed
Closing duplicated issue. Please continue discussing at Issue #7882.
- Has duplicate Feature #12906: do/end blocks work with ensure/rescue/else added
- Project changed from 14 to Ruby master
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0