【问题标题】:Raise Custom Exception if Value is Less than Indicated Value如果值小于指示值,则引发自定义异常
【发布时间】:2022-08-16 22:30:25
【问题描述】:

我正在编写一个用户必须输入整数的代码,并且代码需要在两种情况下使用自定义文本引发自定义异常: a) 如果输入不是整数 b) 如果整数小于 8

我做了第一部分:

begin
  print \"Enter the price: \" 
  price = Integer gets
rescue
  puts \"Error: the entered value is not a number\"
  raise
end

但是如果输入的数字小于 8,我不知道如何引发错误。它需要看起来像这样:

Enter the price:
==> 7

Output:
==> Error: the minimum price needs to be at least 8 euro

抱歉问了这么一个基本问题。我还在学习,异常处理对我来说是一个很新鲜的话题。

    标签: ruby exception


    【解决方案1】:

    您可以像这样引发异常:

    if price < 8
     raise ArgumentError, 'the minimum price needs to be at least 8 euro'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      相关资源
      最近更新 更多