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).

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

One Response to Exception and Error Handling

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