以下是我脚本的代码。
如您所见,我有一个数组和一个索引。我将其传递给名为' raise_clean_exception'的块。它的整数部分实际上引发了一个很好的标准错误异常。当我使用超出范围的索引时,我遇到了一个问题。因此,如果我的数组只有4个元素(0-3)并且我使用9的索引,它将不会引发异常,而是打印出一个空行,因为没有任何内容。为什么要这样做?
#!/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
答案 0 :(得分:7)
考虑使用StandardError的子类IndexError
,该子类特定于您遇到的问题。此外,如果索引超出范围,并且在方法中引发异常时,使用else
可防止打印空格,则隐含begin...end
块。
def raise_clean_exception(arr, index)
Integer(index)
raise IndexError if index.to_i >= arr.length
rescue StandardError
puts "That is an invalid index!"
else
puts "#{arr[index.to_i]}"
end
答案 1 :(得分:5)
访问超出现有元素范围的数组元素将返回nil。这就是Ruby的工作方式。
您可以在“puts”之前添加以下行来捕获该条件...
raise StandardError if index.to_i >= arr.size