How to use custom error messages
当我使用非数字输入测试我的代码时,Ruby会引发一条默认消息。 相反,每当引发异常时,我希望使用默认的
1 | "oops... That was not a number" |
被提出而不是:
1 2 | invalid value for Float():"h " (ArgumentError) |
我编写了下面的代码,受以下文档的启发:
堆栈溢出,
rubylearning,
github上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
以下代码确实表现得像我期望的那样; 我无法理解为什么下面的代码打印我的默认消息,而上面的代码没有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 |
只需像这样修改你的脚本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
您的