When I test my code with a non-numeric input, Ruby raises a default message. Instead, whenever an exception is raised, I would like my custom message to be printed with a default backtrace.inspect
. I expect:
"oops... That was not a number"
to be raised instead of:
invalid value for Float(): "h\n" (ArgumentError)
I wrote the code below, inspired by the following documentation: 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
The following code instead does behave as I expect; I can't see why the code below prints my default message while the code above does not:
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