Ruby - Exception Handling exceptions

Introduction

Ruby rescue clause is used along with begin and end to define blocks of code to handle exceptions. For example:

Demo

begin 
  puts 10 / 0 # w w w  .  ja  v a 2  s.c o m
rescue 
  puts "You caused an error!" 
end

Result

Here, begin...end defines a section where if an exception arises, it's handled with the code inside the rescue block.

Ten divided by zero raises an exception of class ZeroDivisionError.

Being inside a block containing a rescue section means that the exception is handled by the code inside that rescue section.

Rather than existing with a ZeroDivisionError, the text "You caused an error!" is printed to the screen.

Related Topics