I am trying to test my understanding of begin-rescue-end in a method.
For this purpose I created three methods: the first two should open and
print on screen a chosen file, unless the file does not exist; in that
case the method should print on screen an error message of my choice.
The problem is that the codes do not print my message but the default
message.
The third code should print on screen the number the user chooses,
unless the user’s choice is not numeric: in that case the code should
print on screen an error message. In this second code the error message
of my choice is printed out even if I choose a number.
Does any of you have any idea on where am I mistaking?
Thanks in advance for your help
p.s. I attached a file containing the three methods: the first two
dealing with printing the content of a file on screen, the last should
take the input from the user and print it on screen in case it is a
number, otherwise an error message should appear: non of these codes
work
I think the best choice is to use Integer(gets) or Float(gets) because
if the input is a string, #to_i or #to_f convert it to zero with no
error messages, zero being a number.
Using Integer(gets) or Float(gets), when the input is not a number the
error message sent on screen is not my message: ‘That was not a number.’
but a totally different one: invalid value for Float(): “dghj\n”.
This also happens for my methods ‘open_a_file’ and ‘open_a_file2’.
I saw the use of “rescue Exception” at the following address:
If you would not recommend the use of “rescue Exception” what would you
recommend? In my case what I wanted was the message method to print on
screen my error message and not a default one.