Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created February 9, 2015 18:44
Show Gist options
  • Save mayfer/351554a5a812c661ff7e to your computer and use it in GitHub Desktop.
Save mayfer/351554a5a812c661ff7e to your computer and use it in GitHub Desktop.
exceptions
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