I like Exceptions. They’re a very useful concept for raising and handling errors at the correct level without cluttering our code. Coming from C# the way Exceptions work in Ruby are intuitive to me, but there are actually a few extra features which aren’t available in the .NET world.
Basics First
To illustrate Exceptions, I’ve created a very simple class that simulates interaction with a remote resource.
Let’s see what happens when we raise a simple exception.
As you would probably expect, our little application exits immediately and reports the type and message of the exception that was raised. So far so good.
Handling Exceptions
Let’s see how we handle an exception.
Pretty neat. This is probably not very good code, since we’re handling the global Exception class which is bad practice – we should try to handle only specific Exception classes.
We can also handle multiple Exception classes in one block.
Ensure code is executed
We can also ensure that a block of code is executed – for example, we might want to add some logging code around the accessing of the remote resource.
As the name implies, ensure ensures that a certain block of code is executed – as you can see from the output. C# users will immediately recognize a strong similarity to the finally keyword in .NET.
Ruby also introduces the else clause – this will only execute if no errors were encountered. The else clause must go before the ensure clause and after any rescue clauses.
This is probably quite useful in certain scenarios.
Retry the block
Ruby also allows us to correct the cause of the exception and retry the block. For example, since my remote resource is a little unstable I might choose to retry the block until the resource is returned.
As you might imagine, it’s one of the easiest ways of creating an infinite loop so use with care. In fact, I actually managed to create an infinite loop while writing this post!
Conclusion
As someone coming from C# the Exception handling in Ruby seems very intuitive to me. The additional functionality (else and retry) could also be very useful in certain scenarios.