2018-03-04 10:09:32 -05:00
|
|
|
require_relative '../spec_helper'
|
2017-05-07 08:04:49 -04:00
|
|
|
|
|
|
|
describe "The throw keyword" do
|
|
|
|
it "abandons processing" do
|
|
|
|
i = 0
|
|
|
|
catch(:done) do
|
|
|
|
loop do
|
|
|
|
i += 1
|
|
|
|
throw :done if i > 4
|
|
|
|
end
|
|
|
|
i += 1
|
|
|
|
end
|
|
|
|
i.should == 5
|
|
|
|
end
|
|
|
|
|
|
|
|
it "supports a second parameter" do
|
|
|
|
msg = catch(:exit) do
|
|
|
|
throw :exit,:msg
|
|
|
|
end
|
|
|
|
msg.should == :msg
|
|
|
|
end
|
|
|
|
|
|
|
|
it "uses nil as a default second parameter" do
|
|
|
|
msg = catch(:exit) do
|
|
|
|
throw :exit
|
|
|
|
end
|
|
|
|
msg.should == nil
|
|
|
|
end
|
|
|
|
|
|
|
|
it "clears the current exception" do
|
|
|
|
catch :exit do
|
|
|
|
begin
|
|
|
|
raise "exception"
|
|
|
|
rescue
|
|
|
|
throw :exit
|
|
|
|
end
|
|
|
|
end
|
|
|
|
$!.should be_nil
|
|
|
|
end
|
|
|
|
|
|
|
|
it "allows any object as its argument" do
|
|
|
|
catch(1) { throw 1, 2 }.should == 2
|
|
|
|
o = Object.new
|
|
|
|
catch(o) { throw o, o }.should == o
|
|
|
|
end
|
|
|
|
|
|
|
|
it "does not convert strings to a symbol" do
|
2019-07-27 06:40:09 -04:00
|
|
|
-> { catch(:exit) { throw "exit" } }.should raise_error(ArgumentError)
|
2017-05-07 08:04:49 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
it "unwinds stack from within a method" do
|
|
|
|
def throw_method(handler, val)
|
|
|
|
throw handler, val
|
|
|
|
end
|
|
|
|
|
|
|
|
catch(:exit) do
|
|
|
|
throw_method(:exit, 5)
|
|
|
|
end.should == 5
|
|
|
|
end
|
|
|
|
|
|
|
|
it "unwinds stack from within a lambda" do
|
2019-07-27 06:40:09 -04:00
|
|
|
c = -> { throw :foo, :msg }
|
2017-05-07 08:04:49 -04:00
|
|
|
catch(:foo) { c.call }.should == :msg
|
|
|
|
end
|
|
|
|
|
|
|
|
it "raises an ArgumentError if outside of scope of a matching catch" do
|
2019-07-27 06:40:09 -04:00
|
|
|
-> { throw :test, 5 }.should raise_error(ArgumentError)
|
|
|
|
-> { catch(:different) { throw :test, 5 } }.should raise_error(ArgumentError)
|
2017-05-07 08:04:49 -04:00
|
|
|
end
|
|
|
|
|
2017-10-28 11:15:48 -04:00
|
|
|
it "raises an UncaughtThrowError if used to exit a thread" do
|
|
|
|
catch(:what) do
|
|
|
|
t = Thread.new {
|
|
|
|
-> {
|
2017-05-07 08:04:49 -04:00
|
|
|
throw :what
|
2017-10-28 11:15:48 -04:00
|
|
|
}.should raise_error(UncaughtThrowError)
|
|
|
|
}
|
|
|
|
t.join
|
|
|
|
end
|
2017-05-07 08:04:49 -04:00
|
|
|
end
|
|
|
|
end
|