# How to Handle Exceptions in Ruby

RubyServer Side ProgrammingProgramming

#### Learn Ruby on Rails from Scratch

46 Lectures 9.5 hours

#### Master Ruby on Rails - For Beginners

97 Lectures 7.5 hours

#### Dissecting Ruby on Rails 5 - Become a Professional Developer

227 Lectures 40 hours

Exceptions in programming are errors that occur at runtime. They are hard to handle in an effective manner, but it is important to handle them, else they halt the program execution.

Some of the common exceptions that one can encounter are −

• trying to open a file that is not there,

• dividing the number with zero,

• running out of memory etc.

Now let's take a couple of examples to demonstrate how exceptions halt the execution of a Ruby program.

## Example 1

Consider the code shown below.

taking two integer value
$First = 10;$Second = 0;

# divide by zero error
$Third =$First / $Second; puts "The Result is: #{$Third}"

In this program, we are having two integers and we are dividing them, where the second integer is a zero, which will result in an exception.

## Output

It will produce the following output.

main.rb:1:in ': undefined local variable or method value' for main:Object (NameError)

We saw that in the above example, we encountered an exception that occurred due to some error in the code, but we can even create our own exceptions with the help of the raise keyword.

## Example 2

Consider the code shown below.

# defining a method
def raising_exception
puts 'Before Exception!'

# using raise to create exception
raise 'Exception Created'
puts 'After Exception Arise'
end

# Calling the method
raising_exception

In this program, we are creating a new exception and then we are having two logs in the method where the exception is raised.

It should be noted that once an exception is encountered, there won't be any logs that will be printed after it, as the program comes to a halt.

## Output

It will produce the following output.

Before Exception!
Traceback (most recent call last):
1: from main.rb:13:in <main>'
main.rb:7:in raising_exception': Exception Created (RuntimeError)

## Example 3

Now that we have seen how an exception works and how we can create an exception for ourselves, let's see how we can handle that exception through an example. Consider the code shown below

# defining a method
def rescue_from_raise
begin
puts 'Before Exception!'

# using raise to create an exception
raise 'Exception Created!'
puts 'After Exception!'

# using Rescue method
rescue
puts 'Saved!'
end

puts 'Outside!'
end

# calling method
rescue_from_raise

## Output

It will produce the following output.

Before Exception!
Saved!
Outside!
Updated on 12-Apr-2022 08:05:57