Open In App

Raising Exceptions in Ruby

Last Updated : 18 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the program’s instructions. As we know, the code enclosed between begin and end block is totally secured for handling Exceptions and the rescue block tells the ruby, the type of exception is to be handled. 
Mainly Runtime Exceptions are handled if they are any error in the code, maybe written by a naive coder, these types of errors may rise “divided by zero error”, “index out of the range error”, etc where the program stops execution whenever these exceptions occur if not handled. By using, raise statement we can raise manual user-defined exceptions. Like, for example, in an ATM transaction program to raise an exception when the user enters an invalid account number to withdraw.
Syntax:

raise exception-type "exception message" condition

Whenever the raise statement is raised it calls the rescue and execution starts from there. raise statement by default raises RuntimeError. 
Example : 
 

Ruby




# Ruby program to illustrate 
# use of raise statement
   
begin
          
    puts 'This is Before Exception Arise!'
          
       # using raise to create an exception  
       raise 'Exception Created!'
    
    puts 'After Exception'
end


Output : 
 

This is Before Exception Arise!
Exception Created!

 

  • Check out the four types of raise statements in the below code: 
    Example : 

Ruby




#!/usr/bin/ruby
puts "type-1\n"
begin
 
  # re-raises the current exception
  # (RuntimeError as they are no current exception)
   raise
rescue
   puts 'Tony got rescued.'
end
puts 'Tony returned safely'
  
puts "\ntype-2\n"
begin
 
   # sets this message to the string in the superclass,
   # this exception will be given top priority in the call stack.
   raise 'Quill got rescued.'
   puts 'quill'  # won't execute
rescue StandardError => e 
   puts e.message
end
puts 'Quill is back to ship.'
  
puts "\ntype-3\n"
begin
# uses the first argument to create an exception
# and then sets the message to the second argument.
   raise StandardError.new 'Groot got rescued.'
rescue StandardError => e  # e=>object
 
  # prints the attached string message.
  puts e.message
end
  
puts "\ntype-4\n"
begin
a = 30
b = 0
# here a conditional statement is added
# to execute only if the statement is true
 
    # raises the exception only if the condition is true
    raise  ZeroDivisionError.new 'b should not be 0' if b == 0
    puts a/b
rescue StandardError => e 
   puts e.message 
end
  
puts
begin
a = 30
 
# changing the b value, it passes the raise and executes further
b = 2
 
    # raises the exception only if the condition is true
    raise  ZeroDivisionError.new 'b should not be 0' if b == 0
    print "a/b = ", a / b
rescue StandardError => e 
   puts e.message 
end


Output: 

type-1
Tony got rescued.
Tony returned safely

type-2
Quill got rescued.
Quill is back to ship.

type-3
Groot got rescued.

type-4
b should not be 0

a/b = 15

 

  • Check out the difference between the Runtime and Raised Exception. 
    Example : 

Ruby




#!/usr/bin/ruby
puts "Raised Exception:\n"
begin
a = 30
b = 0
 
    # raises the exception only if the condition is true
    raise ZeroDivisionError.new 'b should not be 0' if b == 0
    print "a/b = ", (1 + 2) * (a / b)
rescue ZeroDivisionError => e 
   puts e.message
 
   # prints the error stack, but a raised exception has zero stack
   puts e.backtrace
end
  
puts "\nRuntime Exception:\n"
begin
a = 30
b = 0
x=(1 + 2) * (a / b)
 
    # raises the exception only if the condition is true
    raise ZeroDivisionError.new 'b should not be 0' if b == 0
    print "a/b = ", (1 + 2) * (a / b)
rescue ZeroDivisionError => e 
 
  # prints the message=>(divided by 0)
  # from ZeroDivisionError class
   puts e.message
   puts e.backtrace
end


Output: 

Raised Exception:
b should not be 0
(repl):8:in `'
/run_dir/repl.rb:41:in `eval'
/run_dir/repl.rb:41:in `run'


Runtime Exception:
divided by 0
(repl):21:in `/'
(repl):21:in `'
/run_dir/repl.rb:41:in `eval'
/run_dir/repl.rb:41:in `run'

 

  • In above example, Runtime Exception has an error stack


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads