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: , ,     Posted in Development

Rate this article:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Further Reading

One Response to “Exception and Error Handling”

  1. Recent Faves Tagged With "exceptions" : MyNetFaves Says:

    [...] public links >> exceptions Exception and Error Handling First saved by odrazirus | 1 days ago Retirement Savings versus Student Loans First saved by [...]

Leave a Reply