Exception and Error Handling
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).
Tags: error handling, introductory, ruby Posted in
Further Reading
- Undefined Method Foo
- Missing Attribute: foo
- Drilling Down into Validation Failure
- Redirecting in Rails
- Bort: Better Skeleton Applications


September 12th, 2008 at 2:50 am
[...] public links >> exceptions Exception and Error Handling First saved by odrazirus | 1 days ago Retirement Savings versus Student Loans First saved by [...]