Handling Exceptions in Ruby
Applications that are well-designed handle exceptions and errors to prevent crashes. Exceptions occur when any unexpected or exceptional situations arise whilst a program is running. To handle exceptions a programmer will add specific code to handle the error or exceptional state.
In Ruby, you can use a ‘rescue’ block to recover from an exception or just plain ignore the exception and continue on with the program flow. It is common practice to handle the most specific exception to the most general. This way you can accurately control whatever exceptional event occurred in your code.
Here is a block of code that is going to raise an exception, you can run this in IRB:
This will result in a ZeroDivisonError, in my case this is what displayed in IRB
ZeroDivisionError: divided by 0 from (irb):3:in `/' from (irb):3 from /Users/DeonHeyns/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'
So how do I use a ‘rescue’ block to ensure this doesn’t happen? You will want to wrap your code with a ‘begin rescue’ block.
This would handle any exception that might happen in your code, however as I stated earlier it is best practice to handle exceptions from most specific to most general. Enter the following in IRB:
Executing this code will result in ‘StandardError’ being printed to the screen. This is because ZeroDivisionError inherits from StandardError resulting in the first block of code being hit.
Let’s swap this code around this time and see the difference.
This results in ‘ZeroDivisionError’ showing up on the screen and that is exactly what we need, we can now handle the most specific error and the more general thereafter. Don’t believe this is the case? Let’s do another quick test. Go ahead and enter the following code in your IRB session.
The result? The result is that ‘ZeroDivisionError’ is printed to the screen, this proves that the most specific rescue block is hit and if not then the most general rescue block will be hit.
Ruby exception handling is very similar to most other programming languages. If you know that a piece of code is going to raise an exception, you can wrap that code in a ‘begin rescue’ block to ensure that your application does not exit and cause your user to rage.