If you’ve worked with Java or C#, you know about the try/catch block that you use to catch exceptions. Ruby has a similar mechanism, called begin/rescue/end. Let’s say we had a function called risky_operation, that may throw an exception.
Here’s how it would work in Java or C#:
try {
result = riskyOperation();
} catch (Exception e) {
print("Risky operation FAILED: " + e);
}
Here’s the equivalent Ruby code:
begin
result = risky_operation
rescue StandardError => e
puts "Risky operation FAILED: #{e}"
end
StandardError is the ancestor of all errors; if you trap that, you can trap any sort of errors. You can also trap different types of errors, and assign them different names (in our case, we used e).
Pingback: Recent Faves Tagged With "exceptions" : MyNetFaves