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.
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.
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.
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.
if number is 0 even once in the loops we get 10 otherwise we get the number .
- Try, catch, throw and throws in Java
- Ruby | Exception handling
- Ruby | Exception Class and its Methods
- Ruby | Exception Handling in Threads | Set - 1
- Difference between System Level Exception and Application Level Exception in C#
- Scala | Try-Catch Exceptions
- Throw Keyword in Scala
- Exception Handling in PL/SQL
- Scala | Exception Handling
- Exception Handling in Node
- Null Pointer Exception In Java
- Ruby | Module
- Ruby | BigDecimal <= value
- Ruby | Set >= method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.