Created
February 9, 2015 18:44
-
-
Save mayfer/351554a5a812c661ff7e to your computer and use it in GitHub Desktop.
exceptions
This file contains hidden or 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
class EmptyArrayError < StandardError | |
end | |
def avg(arr) | |
if arr.length == 0 | |
raise EmptyArrayError, "Average can only be called on arrays that have values." | |
end | |
sum = 0 | |
arr.each do |i| | |
sum += i | |
end | |
avg = sum/arr.length | |
return avg | |
end | |
begin | |
puts avg([3, 6, 345]) | |
puts avg([]) | |
rescue NameError => a | |
puts "name error" | |
rescue EmptyArrayError => e | |
puts "nothing to see here, #{e.message} #{e.backtrace.inspect}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment