An exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that’s not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is similar raise and rescue keywords, Exceptions can also be handled using catch and throw keywords in Ruby. Throw keyword generates an exception and whenever it is met, the program control goes to the catch statement.
Syntax:
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
The catch block is used to jump out from the nested block and the block is labeled with a name. This block works normally until it encounters with the throw block that’s why catch and throw used instead of raise or rescue.
Example #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 |
Output :
In above example, if the number is 0 then the exception:divide is thrown which returns nothing to the catch statement resulting in “”set to gfg. if the number is 1 then the exception is not thrown and the gfg variable is set to 1.
Example #2: throw with default value.
In the above example when the exception was thrown, the value of variable gfg was set to “”. we can change that by passing the default argument to the throw keyword.
# 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 |
Output :
10
In above example, if number is 0 we get 10. if number is 1 we get 1.
Example 3: nested construct example, here we will see how we can jump out of nested constructs.
# 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 |
Output :
10
if number is 0 even once in the loops we get 10 otherwise we get the number .