当我使用非数字输入测试代码时,Ruby会引发默认消息。相反,每当引发异常时,我都希望使用默认的backtrace.inspect
打印我的自定义消息。我期待:
"oops... That was not a number"
而不是:
invalid value for Float(): "h\n" (ArgumentError)
我编写了以下代码,受以下文档的启发: stackoverflow, rubylearning, github
class MyCustomError < StandardError
def message
"oops... That was not a number"
end
end
def print_a_number
begin
puts "chose a number"
number = Float(gets)
raise MyCustomError unless number.is_a? Numeric
puts "The number you chose is #{number}"
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
以下代码确实表现得像我期望的那样;我无法理解为什么下面的代码打印我的默认消息,而上面的代码没有:
class MyCustomError < StandardError
def message
"The file you want to open does not exist"
end
end
def open_a_file
begin
puts "What file do you want to open?"
file2open = gets.chomp
raise MyCustomError unless File.file?(file2open)
File.open(file2open, 'r') { |x|
while line = x.gets
puts line
end
}
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
答案 0 :(得分:1)
您的unless
条件永远不会为假:Kernel#Float
会引发异常(在这种情况下甚至无法达到您的条件)或返回Float
(这是一个子类) Numeric
)。
答案 1 :(得分:1)
只需像这样修改你的脚本。
class MyCustomError < StandardError
def message
"oops... That was not a number"
end
end
def print_a_number
begin
puts "chose a number"
number = Float(gets) rescue false
raise MyCustomError unless number.is_a? Numeric
puts "The number you chose is #{number}"
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end