Mark24
记录灵感、技术、思考
Ruby的catch与throw
Ruby的 catch 和 throw 不同于其他语言。他的工作方式有点像 Goto。
举个例子:
我们展示下 catch \ throw 正常状态下的执行
# Ruby Program of Catch and Throw Exception
puts '11111'
gfg = catch(:divide) do
puts '22222'
# a code block of catch similar to begin
number = 1
puts '3333'
throw :divide if number == 0
puts '44444'
number # set gfg = number if
# no exception is thrown
end
puts '5555'
p gfg
puts ">>>>"
# 输出:
# 11111
# 22222
# 3333
# 44444
# 5555
# 1
# >>>>
可以看到按照正常输出。
如果我们修改为 number = 0
输出结果将变成
# 11111
# 22222
# 3333
# 5555
# nil
# >>>>
throw 处断开,直接返回到 catch 语句的结果,由于没有值,返回的是 nil
如果我们想赋予默认值可以这样
# Ruby Program of Catch and Throw Exception
puts '11111'
gfg = catch(:divide) do
puts '22222'
# a code block of catch similar to begin
number = 0
puts '3333'
throw :divide, 10 if number == 0
puts '44444'
number # set gfg = number if
# no exception is thrown
end
puts '5555'
p gfg
puts ">>>>"
# 输出
# 11111
# 22222
# 3333
# 5555
# 10
# >>>>
throw的第二个参数是默认值。
当然这样看不出 catch、throw 的特殊性。
# Ruby Program of Catch and Throw Exception
gfg = catch(:divide) do
# a code block of catch similar to begin
100.times do
100.times do
100.times do
# number = rand(10000)
number = 0
# comes out of all of the loops
# and goes to catch statement
throw :divide, 10 if number == 0
end
end
end
number # set gfg = number if
# no exception is thrown
end
puts gfg
# 输出
# 10
可以看出,有这个结构,可以轻松的跳出复杂的嵌套。