Skip to content

Instantly share code, notes, and snippets.

@mkurtikov
Last active April 14, 2016 17:47
Show Gist options
  • Save mkurtikov/f75c41ec2ef09bcf01a416f4e525b984 to your computer and use it in GitHub Desktop.
Save mkurtikov/f75c41ec2ef09bcf01a416f4e525b984 to your computer and use it in GitHub Desktop.
Ruby Exceptions
## http://ruby-doc.org/core-2.3.0/Exception.html
begin
p '1'
1 / 0
rescue
p '2'
end
# "1"
# "2"
begin
raise 'An exception'
rescue Exception => e
p e.message
p e.backtrace
ensure
p "Finally"
end
# "An exception"
#`irb_binding'
# ["(irb):2:in `irb_binding'", ..., "/Users/michael/.rvm/rubies/ruby-2.0.0-p247/bin/irb:12:in `<main>'"]
#Finally
begin
raise Exception.new 'New Exception' if rand > 0.5
rescue Exception => e
puts e.message
else
p "Everything is ok"
ensure
p "Finally"
end
# "Everything is ok" or "New Exception"
# "Finally"
class MyException < Exception; end
begin
raise Exception.new 'My Exception'
rescue MyException => e
p 'Rescued My Exception'
rescue Exception => e
p 'Rescued Exception'
end
# "Rescued Exception"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment