Created
September 30, 2010 02:43
-
-
Save jasonnoble/603934 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22:40:31 /Users/jasonn/source/ruby_koans $ irb | |
>> begin | |
?> nil.some_method_nil_doesnt_know_about | |
>> rescue Exception => ex | |
>> puts ex.class | |
>> puts ex.message | |
>> end | |
NoMethodError | |
undefined method `some_method_nil_doesnt_know_about' for nil:NilClass | |
=> nil | |
>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 2 is the begin block. The begin keyword to Ruby tells Ruby that you're going to execute some code that may throw an exception. Line 3 does in fact throw an exception.
Line 4 is the rescue block. This line tells Ruby that if an exception of type "Exception" is thrown, catch that exception and store it in the variable ex.
Line 5 and 6 calls two methods on the Exception (ex) that was thrown. Line 5 prints out what type/class the exception was, Line 6 prints out the corresponding error message.
Line 7 ends the program.
After typing end into irb, it executes the code. It runs line 3, which raises a "NoMethodError" exception, which our rescue block catches. Our rescue block tells it to print out the type (output line 8) and the error message (output line 9).