Ruby 中的捕获和抛出异常
异常是Exception类的对象或该类的子对象。当程序在执行过程中达到未定义的状态时,就会发生异常。现在程序不知道该怎么做,所以它引发了一个异常。这可以由 Ruby 自动或手动完成。 Catch and Throw类似于raise和rescue关键字,在 Ruby 中也可以使用catch和throw关键字来处理异常。 Throw 关键字生成一个异常,只要遇到它,程序控制就转到 catch 语句。
句法:
catch :lable_name do
# matching catch will be executed when the throw block encounter
throw :lable_name condition
# this block will not be executed
end
catch 块用于从嵌套块中跳出,并用名称标记该块。这个块正常工作,直到遇到 throw 块,这就是为什么使用 catch 和 throw 而不是 raise 或 rescue。
示例 #1:
# Ruby Program of Catch and Throw Exception
gfg = catch(:divide) do
# a code block of catch similar to begin
number = rand(2)
throw :divide if number == 0
number # set gfg = number if
# no exception is thrown
end
puts gfg
输出 :
在上面的示例中,如果数字为 0,则抛出异常:除法,它不向 catch 语句返回任何内容,导致“”设置为 gfg。如果数字为 1,则不抛出异常,并将 gfg 变量设置为 1。
示例 #2:使用默认值抛出。
在上面的例子中,当异常被抛出时,变量 gfg 的值被设置为“”。我们可以通过将默认参数传递给 throw 关键字来改变它。
# Ruby Program of Catch and Throw Exception
gfg = catch(:divide) do
# a code block of catch similar to begin
number = rand(2)
throw :divide, 10 if number == 0
number # set gfg = number if
# no exception is thrown
end
puts gfg
输出 :
10
在上面的例子中,如果数字是 0,我们得到 10。如果数字是 1,我们得到 1。示例 3:嵌套构造示例,这里我们将看到如何跳出嵌套构造。
# 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)
# 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
如果 number 在循环中甚至一次为 0 ,我们得到 10 ,否则我们得到 number 。