How to indicate that something has gone wrong?

An exception object is raised (or thrown).

Exception can occur during execution of code. By default, ruby excution ends when an exception occurs. But, you can declare exception handlers.

Download Free Ruby Ebook

Exceptions in ruby

Example

The program below raises an exception whenever the method raise_exception is called.

1
2
3
4
5
6
7
8
#!/usr/bin/ruby

def raise_exception
puts 'Before execution.'
raise 'An error has occured'
puts 'Does Ruby get here?'
end
raise_exception

This wil show:

1
2
3
4
Before execution.
Traceback (most recent call last):
1: from g.rb:6:in `<main>'
g.rb:3:in `raise_exception': An error has occured (RuntimeError)

This raises an exception using the RuntimeError class.

Practical use

Exceptions can be handled with the rescue keyword.
In the example below we raise an exception and handle it:

1
2
3
4
5
6
7
8
9
def example
begin
raise StandardError
rescue StandardError => e
puts 'Handling exception'
end
end

example

Lets create a situation in which Ruby raises an exception, we’ll divide by zero:.

1
2
3
4
5
6
7
def example
x = 1 / 0
rescue ZeroDivisionError => e
puts 'Handling exception'
end

example

Instead of crashing, Ruby handles the exception and continues execution.

Custom Exceptions

You can use other classes to generate errors, like a custom class:

1
2
3
4
5
6
7
8
class CustomError < StandardError
end

def raise_exception
puts 'Before execution.'
raise CustomError, 'An error has occured'
end
raise_exception