Ruby - Arrays, bounds, and raising exceptions
arrays, exception, indexoutofboundsexception, ruby
Solution
Accessing an array element that's outside the range of existing elements returns nil. That's just the way Ruby works.
You could add the following line before the "puts" to trap that condition...
raise StandardError if index.to_i >= arr.size
Problem
Below is the code for my script. As you can see, i have an array, and an index. I pass that to the block called 'raise_clean_exception'. The integer part of it does actually raise a Standard Error exception which is great. I have an issue when I use an index that is out of bounds. So if my array only has 4 elements (0-3) and I use an index of 9, it will not raise the exception, and instead it prints out a blank line because nothing is there. Why would it do this? ``` #!/usr/bin/ruby puts "I will create a list for you. Enter q to stop creating the list." array = Array.new i = 0 input = '' print "Input a value: " #get the value from the user input = STDIN.gets.chomp while input != 'q' do #keep going until user inputs 'q' array[i] = input #store the value in an array of strings i += 1 #increment out index where the inputs are stored print "Input a value: " #get the value from the user input = STDIN.gets.chomp end #'q' has been entered, exit the loop or go back through if not == 'q' def raise_clean_exception(arr, index) begin Integer(index) puts "#{arr[index.to_i]}" # raise "That is an invalid index!" rescue StandardError => e # to know why I used this you can google Daniel Fone's article "Why you should never rescue exception in Ruby" puts "That is an invalid index!" end # puts "This is after the rescue block" end # now we need to access the array and print out results / error messages based upon the array index value given by the user # index value of -1 is to quit, so we use this in our while loop index = 0 arrBound = array.length.to_i - 1 while index != '-1' do print "Enter an index number between 0 and #{arrBound} or -1 to quit: " index = STDIN.gets.chomp if index == '-1' exit "Have a nice day!" end raise_clean_exception(array, index) end ```