Ruby ignores rescue ArgumentError
Asked Answered
M

2

9

When I run the following, rescue seems to be ignored for ArgumentError. The ArgumentError error message from Ruby appears on the console, but my puts message does not. I tried rescue with TypeError and ZeroDivisionError, and it worked.

def divide(a, b)
    begin
        a.to_s + ' divided by ' + b.to_s + ' is ' + (a/b).to_s
    rescue ArgumentError
        puts 'there must be two arguments'
    end 
end

divide(4)
Miserly answered 21/5, 2012 at 21:26 Comment(0)
B
9

The exception is not thrown inside the function, but at the point where it is called, so you need to catch it somewhere else:

def divide(a, b)
  a.to_s + ' divided by ' + b.to_s + ' is ' + (a/b).to_s
end

begin
  divide(4)
rescue ArgumentError
  puts 'there must be two arguments'
end

While that works, catching ArgumentError is a very bad idea, as it indicates an error in your code which you shouldn't be able to recover from.

Birch answered 21/5, 2012 at 21:31 Comment(0)
F
1

The rescue-ing will be done for this part of code : a.to_s + ' divided by ' + b.to_s + ' is ' + (a/b).to_s. Your exception is triggered not in the method, but at calling-time, if you see what I mean.

Fredericton answered 21/5, 2012 at 21:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.