Monthly Archives: September 2015

Handling Ruby Exceptions and Errors

How to handle exceptions in Ruby? What do `raise` and `rescue` do?

def walk_the_dog(dog)
if dog == nil or dog.size == 0
raise"Can't walk nothing")
puts "Walking #{dog}"

You can use a raise here, to make sure that there is always a dog when you puts "Walking #{dog}". Note that fail is the same raise.

If this raise gets called, nothing after that line will be run.

Exception Handling

If you don’t want your code to just stop when it hits a particular error, you can use rescue, to stop the programme from ending.

Use a begin and end block to handle exceptions and use one or more rescue clauses to tell Ruby what kind of exceptions you want to handle

def raise_an_error
raise 'An error occured.'
puts 'Programme rescued.'

Anything after the raise and before the rescue won’t be run, but anything after the rescue WILL be run.

You can also put a parameter on rescue so you can tell your programme to ONLY rescue certain kinds of errors (that is, the ones you think are acceptable for the circumstances).


rescue StandardError => e

if you don’t say what kind of error, the code will assume StandardError.

rescue StandardError => e
you can shortcut it by
rescue => e
and it will assume you mean Standard Error

It’s important to note that the exception names you use are class names, so if you rescue, for example, StandardError, you will rescue any errors that inherit from that.

You can also create your own exception classes, and you probably want them to inherit from StandardError.

So for example, you probably never want to go
rescue Exception
because this will rescue every exception, because all exceptions inherit from the Exception class.

Errors that inherit from StandardError are NoMethodError, TypeError, RuntimeError, but you can see the whole Exception hierarchy like here

Testing Exceptions

assert_raise(TriangleError) do triangle(0, 0, 0) end

Tests if the given block raises an exception. Acceptable exception types maye be given as optional arguments. If the last argument is a String, it will be used as the error message.



Leave a reply