Ruby ignores saving ArgumentError

When I run the following, the rescue seems to be ignored for an ArgumentError. The ArgumentError error message from Ruby appears on the console, but my puts message does not. I tried to save using 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) 
+6
source share
2 answers

An exception is not thrown inside the function, but in the place 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 this works, catching an ArgumentError is a very bad idea, as it indicates an error in the code that you cannot recover from.

+8
source

Salvation will be done for this part of the code: a.to_s + ' divided by ' + b.to_s + ' is ' + (a/b).to_s . Your exception is not triggered in the method, but during the call, if you understand what I mean.

+1
source

Source: https://habr.com/ru/post/916306/


All Articles