Handling errors with exceptions
Raising exceptions is the most common way to handle errors in Ruby. All core methods in Ruby can raise an exception when called incorrectly. The easiest way to get a core method to trigger an exception is to pass it an incorrect number of arguments, as shown in the following code:
"S".length(1) # ArgumentError (wrong number of arguments)
We can also get a core method to trigger an exception when passing the wrong type of argument:
'S'.count(1) # TypeError (no implicit conversion of Integer into String)
In almost all cases, any unexpected or uncommon error should be raised as an exception, and not handled via a return value. Otherwise, as shown in the previous section, you end up with a case where the error is silently ignored. In the previous section, you saw an example where the update
method using a return value to signal an error resulted in data loss. However, there are other cases where the results are even worse...