Ruby raise and rescue: why my code does not work?

Hi,

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

The number is a String because it was collected using “gets”.

If you want to convert the input to a number and raise an exception when
it is invalid, you can use something like Integer(gets), or Float(gets).

If you want to attempt conversion but set the variable to a zero on
error, you could use something like #to_i or #to_f.

I would also recommend avoiding “rescue Exception” since that will
rescue everything, even mistakes in your code.

Thanks Joel,

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:

http://rubylearning.com/satishtalim/ruby_exceptions.html

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.

I modified my original code and still am unable to load my custom
message.
I attached the code as a file (raise&rescue.rb).

I used the example on Float(gets): if the input from the user is not
Numeric my error message should be printed on screen, but it is not.

Any help will be appreciated.

Thanks

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs