×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

How to raise exceptions in Ruby?

By IncludeHelp Last updated : December 03, 2024

We know that an exception is something that disturbs the easy flow of the program or you can say that it is the unexpected or abnormal event that occurs at the runtime. You must have seen that any code which is written between begin and end block is enough capable to handle any exception but the rescue keyword informs us with the type of exception ruby is going to handle. Ruby is capable to handle any Runtime Exceptions if they create any error in the code and disturbs the flow of the program and these types of error may result in "index out of range exception", "divided by zero error" and so on. If these errors are not handled, the program execution stops.

Raising Exceptions

Whenever there is a call to raise a statement then the pointer goes to the rescue block and the execution takes place from there. Let us understand this with the help of program codes and syntax.

Syntax

raise exception-type "exception_message" condition

Example 1

=begin 
  Ruby program to demonstrate use of raise statement 
=end  

begin
  puts "Before the Exception arises!"
  raise "Creation of Exception done successfully!"
  puts "After the Exception arises!"
end

Output

Before the Exception arises!
main.rb:7:in `<main>': Creation of Exception done successfully! (RuntimeError)

Explanation

In the above code, you can observe that we have raised an exception with the help of the raise keyword and the statement which is written before the raise block has been printed on the other hand the statement which is written after the raise statement has not been executed because raise statement disturbs or stops the execution of the program.

Example 2

=begin 
  Ruby program to demonstrate use of raise statement 
=end  

puts "Use of Raise statement. Exception Raised"

begin
  a = 50
  b = 0
  raise ZeroDivisionError.new "the value of b should not be 0" if b == 0
  print "a/b = ", (a / b) 
  rescue ZeroDivisionError => e   
    puts e.message 
    puts e.backtrace 
end

Output

Use of Raise statement. Exception Raised
the value of b should not be 0
main.rb:10:in `<main>'

Explanation

In the above code you can observe that the exception is raised if the raise condition evaluates to be true and ultimately it is because the value of b is 0. e is the object of ZeroDivisionError and the methods e.message and e.backtrack are used to print the error message and error stack respectively.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.