Wanted to talk a bit about exception handling in the language. It looks/works like something in between Python and Java, but with some cool extra features. Here's a short little intro:
In Ruby, the equivalent of Java's explicit throw is the explicit raise.
def intentional_raise puts 'This is intentional I swear.' raise 'Oh %&*#!' puts 'No but seriously I meant to do that.' end intentional_raise
Typing all of this into the interactive ruby shell (irb), we get:
This is intentional I swear.
RuntimeError: Oh %&*#!
from (irb):3:in `intentional_raise'
from (irb):6
from C:/Ruby193/bin/irb:12:in `<main>'
But say we want recover from the exception in some way, and maybe retrieve some info from it. We can use rescue for this.
def kentucky puts 'Well hi!' raise 'I was raised in Kentucky.' rescue Exception => e puts e.message end kentucky
This time we simply get the message from the Exception, rather than having to see all those ugly details:
Well hi!
I was raised in Kentucky.
As one might hope, you can also catch specific kinds of exceptions. And heck, a single rescue block can catch more than one kind, if you'd like! (Also note that you don't have to do all this stuff inside a function. Cuz that would be stupid.)
begin raise NameError, 'Your name is so horrible that I just had to say something.' x = 1/0 rescue NameError, ZeroDivisionError print 'I either caught myself before I said that rude thing out loud ' puts 'or saved the world from your negligence in trying to divide by zero.' puts end begin raise SecurityError, 'During the debate festivities, not all parts of the perimeter were guarded.' rescue SecurityError print 'Everything turned out okay at the debate festival, ' puts 'in spite of potential security issues.' puts end begin raise 'Come at me bro! Do you even lift?!' rescue # could also say rescue Exception [or rescue RuntimeError, in this case] print 'I don\'t have a plan for dealing with any particular exceptions, ' print 'and I\'m especially afraid of that aggressive one that speaks in memes, ' puts 'so I\'ll just re-raise anything I run into.' puts raise end
Here, we get (note that this one wasn't run from irb):
I either caught myself before I said that rude thing out loud or saved the world from your negligence in trying to divide by zero.
Everything turned out okay at the debate festival, in spite of potential security issues.
I don't have a plan for dealing with any particular exceptions, and I'm especially afraid of that aggressive one that speaks in memes, so I'll just re-raise anything I run into.
C:/Program Files (x86)/Notepad++/exceptionTest.rb:17:in `<main>': Come at me bro! Do you even lift?! (RuntimeError)