An an equivalent snippet of ruby..

$ irb
irb(main):001:0> def divide(x, y)
irb(main):002:1>     begin
irb(main):003:2*         result = x / y
irb(main):004:2>         puts "result is", result
irb(main):005:2>     rescue ZeroDivisionError
irb(main):006:2>         puts "division by zero!"
irb(main):007:2>         raise Exception('division by zero')
irb(main):008:2>     ensure
irb(main):009:2*         puts "executing finally clause"
irb(main):010:2>     end
irb(main):011:1> end
=> nil
irb(main):012:0>
irb(main):013:0*
irb(main):014:0* divide(2, 1)
result is
2
executing finally clause
=> nil
irb(main):015:0>
irb(main):016:0* divide(2, 0)
division by zero!
executing finally clause <====== The interesting part
NoMethodError: undefined method `Exception' for main:Object
from (irb):7:in `divide'
 from (irb):16
from :0
irb(main):017:0>
irb(main):018:0* divide("2", "1")
executing finally clause
NoMethodError: undefined method `/' for "2":String
from (irb):3:in `divide'
from (irb):18
 from :0

Thanks,
Kiall


On Tue, Feb 28, 2012 at 4:54 PM, Kiall Mac Innes <ki...@managedit.ie> wrote:

> On Tue, Feb 28, 2012 at 4:48 PM, Tom Boutell <t...@punkave.com> wrote:
>
>> On Tue, Feb 28, 2012 at 11:32 AM, Kiall Mac Innes <ki...@managedit.ie>
>> wrote:
>> > Yes, You could abstract the try/catch into a new (and un-needed)
>> function
>> > to try and emulate the behavior of finally.. Unless, for example, you
>> > re-throw the exception after logging in the catch.
>>
>> 'finally' doesn't run for stuff that throws an exception not caught in
>> the try { } block, or an exception thrown again in the catch { } block
>> - does it?
>>
>> I would hope not, since that means "something this block of code did
>> not anticipate at all - another sort of exceptional situation
>> altogether" and really should not run any more local code, nothing
>> until and unless there is a catch block somewhere further up that does
>> catch that exception.
>>
>
> I would indeed expect the finally to run regardless of what happens in the
> catch block.
>
> $ python
> >>> def divide(x, y):
> ...      try:
> ...          result = x / y
> ...      except ZeroDivisionError:
> ...          print "division by zero!"
> ...          raise Exception('division by zero')
> ...      else:
> ...          print "result is", result
> ...      finally:
> ...          print "executing finally clause"
> ...
> >>> divide(2, 1)
> result is 2
> executing finally clause
> >>>
> >>> divide(2, 0)
> division by zero!
> executing finally clause <====== The interesting part
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 6, in divide
> Exception: division by zero
> >>>
> >>> divide("2", "1")
> executing finally clause
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in divide
> TypeError: unsupported operand type(s) for /: 'str' and 'str'
>

Reply via email to