try catch ruby code example

Example 1: ruby try catch

begin  # "try" block
    puts 'I am before the raise.'  
    raise 'An error has occurred.' # optionally: `raise Exception, "message"`
    puts 'I am after the raise.'   # won't be executed
rescue # optionally: `rescue Exception => ex`
    puts 'I am rescued.'
ensure # will always get executed
    puts 'Always gets executed.'
end

Example 2: rails begin rescue

begin
  3 + '4'
rescue => e
  puts e.class
  puts e.message
  puts e.trace
end

Tags:

Ruby Example