Ruby - 数组、边界和引发异常

标签 ruby arrays exception-handling indexoutofboundsexception

下面是我的脚本代码。

如您所见,我有一个数组和一个索引。我将其传递给名为“raise_clean_exception”的 block 。它的整数部分确实引发了一个很棒的标准错误异常。我在使用越界索引时遇到问题。因此,如果我的数组只有 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

最佳答案

考虑使用 StandardError 的子类 IndexError,它特定于您遇到的问题。此外,使用 else 可以防止在索引超出范围时打印空格,并且在方法内引发异常时,隐含了 begin...end block 。

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

关于Ruby - 数组、边界和引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22647254/

相关文章:

ruby - 如何使用 Selenium Ruby 滚动到底部?

ruby - 一元运算符和在 Ruby 中将 proc 作为参数传递

java - 来自控制台的字符串数组

c++ - C++异常处理如何处理异常派生类?

python - 'finally' 字的 Jython 语法错误

ruby-on-rails - 'array.map' 是否保留原始顺序?

ruby-on-rails - ruby on Rails 应用程序重新启动时执行脚本

用于一维 numpy 数组的 Python 中值滤波器

javascript - 如何根据条件替换 JavaScript 变量?

python - 我想返回一个值并引发异常,这是否意味着我做错了什么?