One of the more important tasks of writing code is handling exceptions. The exception handling block can be defined by the following structure:
begin # statements rescue # handle error else # statements to be executed if there are no errors ensure # statements to be executed whether an error occurred or not end
We can also use the
raise statement to explicitly raise an exception.
This will be clearer by the following example:
begin for i in [1, 2, 3, 4, 5] raise if i == 4 puts i end rescue puts "Reached 4" next else puts "No errors" ensure puts "Iteration completed." end
The output of the code will be as follows:
1 2 3 Reached 4 Iteration completed.