SlideShare a Scribd company logo
RUBY EXCEPTIONS
http://www.tutorialspoint.com/ruby/ruby_exceptions.htm                                          Copyright © tutorialspoint.com



The execution and the exception always go together. If you are opening a file which does not exist then if you did not
handle this situation properly then your program is considered to be of bad quality.

The program stops if an exception occurs. So exceptions are used to handle various type of errors which may occur
during a program execution and take appropriate action instead of halting program completely.

Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end
block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

Syntax :

 begin
 # -
 rescue OneTypeOfException
 # -
 rescue AnotherTypeOfException
 # -
 else
 # Other exceptions
 ensure
 # Always will be executed
 end


Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control
is passed to the block between rescue and end.

For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn.
The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown
exception, or is a superclass of that exception.

In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after
all the rescue clauses.

Example:

 #!/usr/bin/ruby

 begin
    file = open("/unexistant_file")
    if file
       puts "File opened successfully"
    end
 rescue
       file = STDIN
 end
 print file, "==", STDIN, "n"


This will produce following result. You can see that STDIN is substituted to file because open failed.

 #<IO:0xb7d16f84>==#<IO:0xb7d16f84>


Using retry Statement:

You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.
Syntax:

 begin
     # Exceptions raised by this code will
  # be caught by the following rescue clause
 rescue
     # This block will capture all types of exceptions
     retry # This will move control to the beginning of begin
 end


Example:

 #!/usr/bin/ruby

 begin
    file = open("/unexistant_file")
    if file
       puts "File opened successfully"
    end
 rescue
    fname = "existant_file"
    retry
 end


The following is the flow of the process:

       an exception occurred at open

       went to rescue. fname was re-assigned

       by retry went to the beginning of the begin

       this time file opens successfully

       continued the essential process.

NOTE: Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you
use retry for an exception process.

Using raise Statement:

You can use raise statement to raise an exception. The following method raises an exception whenever it's called. It's
second message will be printed. Program

Syntax:

 raise

 OR

 raise "Error Message"

 OR

 raise ExceptionType, "Error Message"

 OR

 raise ExceptionType, "Error Message" condition


The first form simply reraises the current exception (or a RuntimeError if there is no current exception). This is used in
exception handlers that need to intercept an exception before passing it on.
The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then
raised up the call stack.

The third form uses the first argument to create an exception and then sets the associated message to the second
argument.

The fourth form is similar to third form but you can add any conditional statement like unless to raise an exception.

Example:

 #!/usr/bin/ruby

 begin
     puts 'I am before the raise.'
     raise 'An error has occurred.'
     puts 'I am after the raise.'
 rescue
     puts 'I am rescued.'
 end
 puts 'I am after the begin block.'


This will produce following result:

 I am before the raise.
 I am rescued.
 I am after the begin block.


One more example showing usage of raise:

 #!/usr/bin/ruby

 begin
   raise 'A test exception.'
 rescue Exception => e
   puts e.message
   puts e.backtrace.inspect
 end


This will produce following result:

 A test exception.
 ["test.rb:4"]


Using ensure Statement:

Sometimes you need to guarantee that some processing is done at the end of a block of code, regardless of whether an
exception was raised. For example, you may have a file open on entry to the block, and you need to make sure it gets
closed as the block exits.

The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be
executed as the block terminates. It doesn't matter if the block exits normally, if it raises and rescues an exception, or if
it is terminated by an uncaught exception . the ensure block will get run.

Syntax:

 begin
    #.. process
    #..raise exception
 rescue
    #.. handle error
 ensure
#.. finally ensure execution
    #.. This will always execute.
 end


Example:

 begin
   raise 'A test exception.'
 rescue Exception => e
   puts e.message
   puts e.backtrace.inspect
 ensure
   puts "Ensuring execution"
 end


This will produce following result:

 A test exception.
 ["test.rb:4"]
 Ensuring execution


Using else Statement:

If the else clause is present, it goes after the rescue clauses and before any ensure.

The body of an else clause is executed only if no exceptions are raised by the main body of code.

Syntax:

 begin
    #.. process
    #..raise exception
 rescue
    # .. handle error
 else
    #.. executes if there is no exception
 ensure
    #.. finally ensure execution
    #.. This will always execute.
 end


Example:

 begin
  # raise 'A test exception.'
  puts "I'm not raising exception"
 rescue Exception => e
   puts e.message
   puts e.backtrace.inspect
 else
    puts "Congratulations-- no errors!"
 ensure
   puts "Ensuring execution"
 end


This will produce following result:

 I'm not raising exception
 Congratulations-- no errors!
 Ensuring execution


Raised error message can be captured using $! variable.
Catch and Throw:

While the exception mechanism of raise and rescue is great for abandoning execution when things go wrong, it's
sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch
and throw come in handy.

The catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is
executed normally until a throw is encountered.

Syntax:

 throw :lablename
 #.. this will not be executed
 catch :lablename do
 #.. matching catch will be executed after a throw is encountered.
 end

 OR

 throw :lablename condition
 #.. this will not be executed
 catch :lablename do
 #.. matching catch will be executed after a throw is encountered.
 end


Example:

The following example uses a throw to terminate interaction with the user if '!' is typed in response to any prompt.

 def promptAndGet(prompt)
    print prompt
    res = readline.chomp
    throw :quitRequested if res == "!"
    return res
 end

 catch :quitRequested do
    name = promptAndGet("Name: ")
    age = promptAndGet("Age: ")
    sex = promptAndGet("Sex: ")
    # ..
    # process information
 end
 promptAndGet("Name:")


This will produce following result:

 Name: Ruby on Rails
 Age: 3
 Sex: !
 Name:Just Ruby


Class Exception:

Ruby's standard classes and modules raise exceptions. All the exception classes form a hierarchy, with the class
Exception at the top. The next level contains seven different types:

       Interrupt

       NoMemoryError

       SignalException
ScriptError

       StandardError

       SystemExit

There is one other exception at this level, Fatal, but the Ruby interpreter only uses this internally.

Both ScriptError and StandardError have a number of subclasses, but we do not need to go into the details here. The
important thing is that if we create our own exception classes, they need to be subclasses of either class Exception or one
of its descendants.

Let's look at an example:

 class FileSaveError < StandardError
    attr_reader :reason
    def initialize(reason)
       @reason = reason
    end
 end


Now look at the following example which will use this exception:

 File.open(path, "w") do |file|
 begin
     # Write out the data ...
 rescue
     # Something went wrong!
     raise FileSaveError.new($!)
 end
 end


The important line here is raise FileSaveError.new($!). We call raise to signal that an exception has occurred, passing it
a new instance of FileSaveError, with the reason being that specific exception caused the writing of the data to fail.

More Related Content

PPT
Exceptions in java
PPT
Exception handling
PPT
Exceptionhandling
PPT
Exception handling
PPT
exception handling
PPTX
Presentation on-exception-handling
PPTX
Exception handling
DOCX
Java Exception handling
Exceptions in java
Exception handling
Exceptionhandling
Exception handling
exception handling
Presentation on-exception-handling
Exception handling
Java Exception handling

What's hot (20)

PDF
Exception Handling in Python - Rik van Achterberg & Tim Muller
PPTX
Exception handling in JAVA
PPTX
Exception handling in java
PPTX
Exceptionhandling
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PPTX
130410107010 exception handling
PPTX
Exceptions overview
PPTX
Java SE 11 Exception Handling
PPTX
7.error management and exception handling
DOCX
Exception handlingpdf
PPTX
Exception handling in java
PPT
Exception handling in java
PPTX
Java Exception Handling and Applets
PPTX
Exception handling in java
PPT
Exception Handling in JAVA
PPTX
Exception handling in c
PPTX
Chap2 exception handling
PPTX
Exception handling in Java
PPTX
Presentation1
Exception Handling in Python - Rik van Achterberg & Tim Muller
Exception handling in JAVA
Exception handling in java
Exceptionhandling
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
130410107010 exception handling
Exceptions overview
Java SE 11 Exception Handling
7.error management and exception handling
Exception handlingpdf
Exception handling in java
Exception handling in java
Java Exception Handling and Applets
Exception handling in java
Exception Handling in JAVA
Exception handling in c
Chap2 exception handling
Exception handling in Java
Presentation1
Ad

Similar to 21 ruby exceptions (20)

PPT
Exception Handling on 22nd March 2022.ppt
PPT
exceptions in java
PPT
Exception handling in python and how to handle it
PPT
Exception Handling using Python Libraries
PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
PPT
Exceptions in java
PPTX
Exception handling and throw and throws keyword in java.pptx
PPT
Firoze_Errors_Exceptions in python__.ppt
PPT
Firoze_Errors_Exceptions in python__.ppt
PPT
Py-Slides-9.ppt
PDF
Python exception handling
PPTX
Exception handling.pptxnn h
PDF
Java unit 11
PPT
Md07 exceptions&assertion
PDF
JAVA PPT -4 BY ADI.pdf
PPT
Java Exception.ppt
PPTX
Exception Handling in C#
PPTX
presentation-on-exception-handling 1.pptx
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
Exception Handling on 22nd March 2022.ppt
exceptions in java
Exception handling in python and how to handle it
Exception Handling using Python Libraries
Exception Handling,finally,catch,throw,throws,try.pptx
Exceptions in java
Exception handling and throw and throws keyword in java.pptx
Firoze_Errors_Exceptions in python__.ppt
Firoze_Errors_Exceptions in python__.ppt
Py-Slides-9.ppt
Python exception handling
Exception handling.pptxnn h
Java unit 11
Md07 exceptions&assertion
JAVA PPT -4 BY ADI.pdf
Java Exception.ppt
Exception Handling in C#
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling-160611180456 (1).pptx
Ad

More from Walker Maidana (20)

PDF
20 ruby input output
PDF
19 ruby iterators
PDF
18 ruby ranges
PDF
17 ruby date time
PDF
16 ruby hashes
PDF
15 ruby arrays
PDF
14 ruby strings
PDF
13 ruby modules
PDF
12 ruby blocks
PDF
11 ruby methods
PDF
10 ruby loops
PDF
09 ruby if else
PDF
08 ruby comments
PDF
07 ruby operators
PDF
06 ruby variables
PDF
05 ruby classes
PDF
04 ruby syntax
PDF
03 ruby environment
PDF
01 index
PDF
00 ruby tutorial
20 ruby input output
19 ruby iterators
18 ruby ranges
17 ruby date time
16 ruby hashes
15 ruby arrays
14 ruby strings
13 ruby modules
12 ruby blocks
11 ruby methods
10 ruby loops
09 ruby if else
08 ruby comments
07 ruby operators
06 ruby variables
05 ruby classes
04 ruby syntax
03 ruby environment
01 index
00 ruby tutorial

21 ruby exceptions

  • 1. RUBY EXCEPTIONS http://www.tutorialspoint.com/ruby/ruby_exceptions.htm Copyright © tutorialspoint.com The execution and the exception always go together. If you are opening a file which does not exist then if you did not handle this situation properly then your program is considered to be of bad quality. The program stops if an exception occurs. So exceptions are used to handle various type of errors which may occur during a program execution and take appropriate action instead of halting program completely. Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle. Syntax : begin # - rescue OneTypeOfException # - rescue AnotherTypeOfException # - else # Other exceptions ensure # Always will be executed end Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end. For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception. In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses. Example: #!/usr/bin/ruby begin file = open("/unexistant_file") if file puts "File opened successfully" end rescue file = STDIN end print file, "==", STDIN, "n" This will produce following result. You can see that STDIN is substituted to file because open failed. #<IO:0xb7d16f84>==#<IO:0xb7d16f84> Using retry Statement: You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.
  • 2. Syntax: begin # Exceptions raised by this code will # be caught by the following rescue clause rescue # This block will capture all types of exceptions retry # This will move control to the beginning of begin end Example: #!/usr/bin/ruby begin file = open("/unexistant_file") if file puts "File opened successfully" end rescue fname = "existant_file" retry end The following is the flow of the process: an exception occurred at open went to rescue. fname was re-assigned by retry went to the beginning of the begin this time file opens successfully continued the essential process. NOTE: Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process. Using raise Statement: You can use raise statement to raise an exception. The following method raises an exception whenever it's called. It's second message will be printed. Program Syntax: raise OR raise "Error Message" OR raise ExceptionType, "Error Message" OR raise ExceptionType, "Error Message" condition The first form simply reraises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on.
  • 3. The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack. The third form uses the first argument to create an exception and then sets the associated message to the second argument. The fourth form is similar to third form but you can add any conditional statement like unless to raise an exception. Example: #!/usr/bin/ruby begin puts 'I am before the raise.' raise 'An error has occurred.' puts 'I am after the raise.' rescue puts 'I am rescued.' end puts 'I am after the begin block.' This will produce following result: I am before the raise. I am rescued. I am after the begin block. One more example showing usage of raise: #!/usr/bin/ruby begin raise 'A test exception.' rescue Exception => e puts e.message puts e.backtrace.inspect end This will produce following result: A test exception. ["test.rb:4"] Using ensure Statement: Sometimes you need to guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised. For example, you may have a file open on entry to the block, and you need to make sure it gets closed as the block exits. The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn't matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception . the ensure block will get run. Syntax: begin #.. process #..raise exception rescue #.. handle error ensure
  • 4. #.. finally ensure execution #.. This will always execute. end Example: begin raise 'A test exception.' rescue Exception => e puts e.message puts e.backtrace.inspect ensure puts "Ensuring execution" end This will produce following result: A test exception. ["test.rb:4"] Ensuring execution Using else Statement: If the else clause is present, it goes after the rescue clauses and before any ensure. The body of an else clause is executed only if no exceptions are raised by the main body of code. Syntax: begin #.. process #..raise exception rescue # .. handle error else #.. executes if there is no exception ensure #.. finally ensure execution #.. This will always execute. end Example: begin # raise 'A test exception.' puts "I'm not raising exception" rescue Exception => e puts e.message puts e.backtrace.inspect else puts "Congratulations-- no errors!" ensure puts "Ensuring execution" end This will produce following result: I'm not raising exception Congratulations-- no errors! Ensuring execution Raised error message can be captured using $! variable.
  • 5. Catch and Throw: While the exception mechanism of raise and rescue is great for abandoning execution when things go wrong, it's sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy. The catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered. Syntax: throw :lablename #.. this will not be executed catch :lablename do #.. matching catch will be executed after a throw is encountered. end OR throw :lablename condition #.. this will not be executed catch :lablename do #.. matching catch will be executed after a throw is encountered. end Example: The following example uses a throw to terminate interaction with the user if '!' is typed in response to any prompt. def promptAndGet(prompt) print prompt res = readline.chomp throw :quitRequested if res == "!" return res end catch :quitRequested do name = promptAndGet("Name: ") age = promptAndGet("Age: ") sex = promptAndGet("Sex: ") # .. # process information end promptAndGet("Name:") This will produce following result: Name: Ruby on Rails Age: 3 Sex: ! Name:Just Ruby Class Exception: Ruby's standard classes and modules raise exceptions. All the exception classes form a hierarchy, with the class Exception at the top. The next level contains seven different types: Interrupt NoMemoryError SignalException
  • 6. ScriptError StandardError SystemExit There is one other exception at this level, Fatal, but the Ruby interpreter only uses this internally. Both ScriptError and StandardError have a number of subclasses, but we do not need to go into the details here. The important thing is that if we create our own exception classes, they need to be subclasses of either class Exception or one of its descendants. Let's look at an example: class FileSaveError < StandardError attr_reader :reason def initialize(reason) @reason = reason end end Now look at the following example which will use this exception: File.open(path, "w") do |file| begin # Write out the data ... rescue # Something went wrong! raise FileSaveError.new($!) end end The important line here is raise FileSaveError.new($!). We call raise to signal that an exception has occurred, passing it a new instance of FileSaveError, with the reason being that specific exception caused the writing of the data to fail.