Created
May 24, 2012 21:24
-
-
Save mkoby/2784324 to your computer and use it in GitHub Desktop.
Intro to Ruby - 14 - Error Handling
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
2/0 # => ZeroDivisionError | |
# In order to give the user a better error message than "ZeroDivisionError" | |
# we have to wrap the code using begin & rescue keywords so that Ruby knows | |
# that we specifically want to do something if an error is encountered | |
begin | |
2/0 | |
rescue | |
“You can’t divide by ZERO!” | |
end | |
# Result: | |
# => Can’t divide by ZERO!” | |
# Catching a specific Error | |
# You can be specific about the errors you catch, by doing a rescue | |
# specifically on the error you're looking to catch. This allows | |
# you to run code that might be specific to the error. | |
# | |
# As a good practice if you're catching errors, is to catch Exception | |
# so that you have a generic error handling. Don't go crazy and wrap | |
# EVERYTHING but if you're going to catch a specific type of error, | |
# you should also catch Exception so that all other error types get | |
# potentially handled as well. | |
begin | |
2/0 | |
rescue ZeroDivisionError => zde | |
puts zde.message | |
rescue Exception => ex | |
puts “Some other error occured” | |
puts ex.message | |
end | |
# Result: | |
# divided by 0 | |
# => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment