SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
‘Exception Handling in RUBY’




                           ‘Exception Handling in RUBY’

                                          Joy Menon

                   Department of Computer Science and Engineering, IIT Mumbai.


                                     24 November 2004
‘Exception Handling in RUBY’




A Brief Outline

             Exception Handling: WHY?
                     Errors and Error Codes
                     The Need for Exception Handling

             Exception Handling in Ruby:
                     The Exception Class
                     Exception Class Heirarchy
                     Handling Exceptions
                     Raising Exceptions
                     Catch/Throw Clauses


             Conclusions
‘Exception Handling in RUBY’
  Exception Handling: WHY?
     Errors and Error Codes



Errors and Error Codes

              In any programming, occurance of errors is a distinct reality.
              Errors need to be handled gracefully to avoid abrupt failures.
              Code that detects error may not have context to handle it.
                     For example, attempting to open a file that doesn’t exist is
                     acceptable in some circumstances and is a fatal error at other
                     times. What does the file-handling module do?

              Conventionally it was done using error-checking and
              return-codes mechanism.
              Functions were checked for return values, and if the return
              code indicated failure, this code was interpreted and passed
              up the call stack.
‘Exception Handling in RUBY’
  Exception Handling: WHY?
     The Need for Exception Handling



The Need for Exception Handling

             However Error-codes mechanism has following shortcomings:
                     Handling all errors through error codes is simply not possible.
                     Moving error codes up the function call stack is complicated.
                     Managing all the error-codes and associated code is tedious.

             The Exception Handling mechanism addresses these
             shortcomings.
                     Exceptions allow packaging info about error in an object.
                     Exception handling helps propagate object up the call stack.
                     Runtime system locates code that knows to handle the error.


             Exception handling is essential for achieving well-designed object
             oriented code, and therefore Ruby provides a mechanism for same.
‘Exception Handling in RUBY’
  Exception Handling in Ruby
     The Exception Class



The Exception Class

             As in other object oriented languages, Ruby offers a
             mechanism for exception handling.

             When an exception occurs..
                     Object of class Exception, or one of it’s children, created.
                     Exception is associated to message string & a stack backtrace.
                     All information about the exception is packaged in this object.

             IOError, ZeroDivisionError, TypeError, SystemCallError, etc
             are examples of exceptions derived from class Exception.

             Ruby predefines a hierarchy of exceptions: see next slide.
‘Exception Handling in RUBY’
  Exception Class Heirarchy




Exception Class Heirarchy
‘Exception Handling in RUBY’
  User Defined Exceptions




User Defined Exceptions


      User-Defined Exception
             Users can create exception classes of their own.

             These must inherit from class StandardError or its children.

             If they dont, such exceptions will not be detected by default.

             They may include more specific information about the
             exception.
‘Exception Handling in RUBY’
  User Defined Exceptions
     Handling Exceptions



Handling Exceptions
             The basic approach to exception handling involves the use of:
                     Enclose candidate code in begin/end block.
                     Use rescue block to handle specific class of exceptions,
                     where:
                               Report the error,
                               Code to handle detected error,
                               Raise the exception using raise.
                     Use ensure block to ensure execution of some essential code
                     after handling, like deallocation of resources such as DB
                     connections, etc.

             We can draw analogies to C++/Java exception handling:
                 begin/end block for candidate code. (like try block)
                 rescue blocks for handling code. (like catch blocks)
                 raise command for raising the exception. (like throw)
                 ensure command for necessary handling. (like final)
‘Exception Handling in RUBY’
  User Defined Exceptions
     Handling Exceptions



Example: Using rescue, raise and ensure
‘Exception Handling in RUBY’
  User Defined Exceptions
     Handling Exceptions



Handling Exceptions (continued..)


             Variables
                     $ refers to the default global variable that stores the exception
                     object for the exception.
                     stderrobj is an example of user-defined variable storing the
                     reference to the exception object.


             Matching exceptions to correct rescue block is like the case
             statement mechanism,
             object.kindof? result compared to exception types in
             rescue statements.
‘Exception Handling in RUBY’
  User Defined Exceptions
     Raising Exceptions



Raising Exceptions
              Raising exceptions deliberately in code help to trigger alerts
              where errors are expected and need to be handled.

              The raise statement can take the following forms:
                     raise
                     Raises current exception again, or RuntimeError if none.

                     raise <message>
                     Creates new RuntimeError exception, associates it with
                     mentioned string, and raises the exception up the call stack.

                     raise <exception class>, <message>, <call stack>
                     Creates exception with arg-1 used as required exception type,
                     arg-2 as message string, and arg-3 as stack trace.
‘Exception Handling in RUBY’
  User Defined Exceptions
     Raising Exceptions



Example: Typical Usage of raise
‘Exception Handling in RUBY’
  User Defined Exceptions
     The Catch/Throw Clauses



The catch/throw Clauses
             The rescue and raise mechanism is thus used for
             abandoning execution when unwanted errors occur.
             The catch and throw mechanism is used to continue
             execution at some point up the call stack.

             Working of catch/throw:
                     catch defines a block with a specific label.
                     The block is exeuted, typically accross nested functions, till a
                     throw followed by the label is encountered.
                     The call stack is then scoured for a catch block with a
                     matching label.
                     On a match, Ruby rolls back execution to the point and
                     terminates the block.
                     If the throw had an optional 2nd argument, it is returned as
                     value of the catch block.
‘Exception Handling in RUBY’
  User Defined Exceptions
     The Catch/Throw Clauses



Example: Typical usage of catch/throw
‘Exception Handling in RUBY’
  Conclusions




Conclusions

                Exception Handling is essential for managing errors in
                object-oriented code.

                The Ruby Exception Handling mechanism includes:
                     rescue and final clauses - for handling unwanted errors and
                     exit gracefully.

                     raise - for deliberately creating and raising exceptions in
                     code.

                     catch and throw clause - for continuing execution at some
                     point up the function call stack.
‘Exception Handling in RUBY’
  Conclusions




References



             http://www.insula.cz/dali/material/rbycl/.
             http://www.ruby-lang.org/.
             Dave Thomas and Chad Fowler and Andy Hunt.
             Programming Ruby: The Pragmatic Programmers’ Guide.
             Pragmatic Bookshelf, Oct 2004.

Más contenido relacionado

Destacado

Estrellas Del Mundo Del Futbol.Ppt
Estrellas Del Mundo Del Futbol.PptEstrellas Del Mundo Del Futbol.Ppt
Estrellas Del Mundo Del Futbol.Pptguest05295b
 
Flores Obras Divinas Da Natureza Pietro Ubaldi
Flores Obras Divinas  Da Natureza   Pietro UbaldiFlores Obras Divinas  Da Natureza   Pietro Ubaldi
Flores Obras Divinas Da Natureza Pietro Ubaldiguest524d4a
 
Flores Obras Divinas da Natureza - Textos de Pietro Ubaldi
Flores Obras Divinas  da  Natureza - Textos de     Pietro  UbaldiFlores Obras Divinas  da  Natureza - Textos de     Pietro  Ubaldi
Flores Obras Divinas da Natureza - Textos de Pietro Ubaldiguest524d4a
 
Nuevo trabajo de plasticos..!
Nuevo trabajo de plasticos..!Nuevo trabajo de plasticos..!
Nuevo trabajo de plasticos..!Lau93
 
Flores - Obras Divinas da Natureza Pietro Ubaldi
Flores - Obras Divinas  da Natureza   Pietro UbaldiFlores - Obras Divinas  da Natureza   Pietro Ubaldi
Flores - Obras Divinas da Natureza Pietro Ubaldiguest524d4a
 
pruebas de garlomin
pruebas de garlominpruebas de garlomin
pruebas de garlominguestacd629
 
Flores - Obras Divinas da Natureza - Textos de Pietro Ubaldi
Flores -  Obras Divinas  da Natureza - Textos de  Pietro UbaldiFlores -  Obras Divinas  da Natureza - Textos de  Pietro Ubaldi
Flores - Obras Divinas da Natureza - Textos de Pietro Ubaldiguest524d4a
 
Alguns GêNios Da Pintura - Textos de Emmanuel
Alguns GêNios Da Pintura - Textos de EmmanuelAlguns GêNios Da Pintura - Textos de Emmanuel
Alguns GêNios Da Pintura - Textos de Emmanuelguest524d4a
 
IT_job_presentation
IT_job_presentationIT_job_presentation
IT_job_presentationHH_Penza
 
Arturo Love
Arturo LoveArturo Love
Arturo Lovekarisha
 
Baloncesto Javier Rodriguez y Alberto Ruiz
Baloncesto Javier Rodriguez y Alberto RuizBaloncesto Javier Rodriguez y Alberto Ruiz
Baloncesto Javier Rodriguez y Alberto Ruizguest8f54d9
 

Destacado (20)

Estrellas Del Mundo Del Futbol.Ppt
Estrellas Del Mundo Del Futbol.PptEstrellas Del Mundo Del Futbol.Ppt
Estrellas Del Mundo Del Futbol.Ppt
 
Connectedness
ConnectednessConnectedness
Connectedness
 
Modelo FIT
Modelo FITModelo FIT
Modelo FIT
 
Flores Obras Divinas Da Natureza Pietro Ubaldi
Flores Obras Divinas  Da Natureza   Pietro UbaldiFlores Obras Divinas  Da Natureza   Pietro Ubaldi
Flores Obras Divinas Da Natureza Pietro Ubaldi
 
Flores Obras Divinas da Natureza - Textos de Pietro Ubaldi
Flores Obras Divinas  da  Natureza - Textos de     Pietro  UbaldiFlores Obras Divinas  da  Natureza - Textos de     Pietro  Ubaldi
Flores Obras Divinas da Natureza - Textos de Pietro Ubaldi
 
Nuevo trabajo de plasticos..!
Nuevo trabajo de plasticos..!Nuevo trabajo de plasticos..!
Nuevo trabajo de plasticos..!
 
Natalia Oreiroppt
Natalia OreiropptNatalia Oreiroppt
Natalia Oreiroppt
 
Flores - Obras Divinas da Natureza Pietro Ubaldi
Flores - Obras Divinas  da Natureza   Pietro UbaldiFlores - Obras Divinas  da Natureza   Pietro Ubaldi
Flores - Obras Divinas da Natureza Pietro Ubaldi
 
Ron Mueck
Ron MueckRon Mueck
Ron Mueck
 
Tiendademaridos
TiendademaridosTiendademaridos
Tiendademaridos
 
pruebas de garlomin
pruebas de garlominpruebas de garlomin
pruebas de garlomin
 
Ejemplo para Web 2.0
Ejemplo para Web 2.0Ejemplo para Web 2.0
Ejemplo para Web 2.0
 
Flores - Obras Divinas da Natureza - Textos de Pietro Ubaldi
Flores -  Obras Divinas  da Natureza - Textos de  Pietro UbaldiFlores -  Obras Divinas  da Natureza - Textos de  Pietro Ubaldi
Flores - Obras Divinas da Natureza - Textos de Pietro Ubaldi
 
Alguns GêNios Da Pintura - Textos de Emmanuel
Alguns GêNios Da Pintura - Textos de EmmanuelAlguns GêNios Da Pintura - Textos de Emmanuel
Alguns GêNios Da Pintura - Textos de Emmanuel
 
la navidad
la navidadla navidad
la navidad
 
IT_job_presentation
IT_job_presentationIT_job_presentation
IT_job_presentation
 
Arturo Love
Arturo LoveArturo Love
Arturo Love
 
Baloncesto Javier Rodriguez y Alberto Ruiz
Baloncesto Javier Rodriguez y Alberto RuizBaloncesto Javier Rodriguez y Alberto Ruiz
Baloncesto Javier Rodriguez y Alberto Ruiz
 
Tardor
TardorTardor
Tardor
 
Soymaestra( P P Tminimizer)
Soymaestra( P P Tminimizer)Soymaestra( P P Tminimizer)
Soymaestra( P P Tminimizer)
 

Similar a Ruby Exceptions

Unit5 java
Unit5 javaUnit5 java
Unit5 javamrecedu
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in JavaJava2Blog
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event HandlingJava Programming
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Wen-Tien Chang
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 

Similar a Ruby Exceptions (12)

Unit5 java
Unit5 javaUnit5 java
Unit5 java
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
Exception handling
Exception handlingException handling
Exception handling
 

Más de guest0046de

Google 1195446284844957 5
Google 1195446284844957 5Google 1195446284844957 5
Google 1195446284844957 5guest0046de
 
Cute Babies 013703
Cute Babies 013703Cute Babies 013703
Cute Babies 013703guest0046de
 
Cute Babies 013703
Cute Babies 013703Cute Babies 013703
Cute Babies 013703guest0046de
 

Más de guest0046de (7)

Ruby Exceptions
Ruby ExceptionsRuby Exceptions
Ruby Exceptions
 
Ruby Exceptions
Ruby ExceptionsRuby Exceptions
Ruby Exceptions
 
Google 1195446284844957 5
Google 1195446284844957 5Google 1195446284844957 5
Google 1195446284844957 5
 
Sample
SampleSample
Sample
 
Ruby Exceptions
Ruby ExceptionsRuby Exceptions
Ruby Exceptions
 
Cute Babies 013703
Cute Babies 013703Cute Babies 013703
Cute Babies 013703
 
Cute Babies 013703
Cute Babies 013703Cute Babies 013703
Cute Babies 013703
 

Último

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 

Ruby Exceptions

  • 1. ‘Exception Handling in RUBY’ ‘Exception Handling in RUBY’ Joy Menon Department of Computer Science and Engineering, IIT Mumbai. 24 November 2004
  • 2. ‘Exception Handling in RUBY’ A Brief Outline Exception Handling: WHY? Errors and Error Codes The Need for Exception Handling Exception Handling in Ruby: The Exception Class Exception Class Heirarchy Handling Exceptions Raising Exceptions Catch/Throw Clauses Conclusions
  • 3. ‘Exception Handling in RUBY’ Exception Handling: WHY? Errors and Error Codes Errors and Error Codes In any programming, occurance of errors is a distinct reality. Errors need to be handled gracefully to avoid abrupt failures. Code that detects error may not have context to handle it. For example, attempting to open a file that doesn’t exist is acceptable in some circumstances and is a fatal error at other times. What does the file-handling module do? Conventionally it was done using error-checking and return-codes mechanism. Functions were checked for return values, and if the return code indicated failure, this code was interpreted and passed up the call stack.
  • 4. ‘Exception Handling in RUBY’ Exception Handling: WHY? The Need for Exception Handling The Need for Exception Handling However Error-codes mechanism has following shortcomings: Handling all errors through error codes is simply not possible. Moving error codes up the function call stack is complicated. Managing all the error-codes and associated code is tedious. The Exception Handling mechanism addresses these shortcomings. Exceptions allow packaging info about error in an object. Exception handling helps propagate object up the call stack. Runtime system locates code that knows to handle the error. Exception handling is essential for achieving well-designed object oriented code, and therefore Ruby provides a mechanism for same.
  • 5. ‘Exception Handling in RUBY’ Exception Handling in Ruby The Exception Class The Exception Class As in other object oriented languages, Ruby offers a mechanism for exception handling. When an exception occurs.. Object of class Exception, or one of it’s children, created. Exception is associated to message string & a stack backtrace. All information about the exception is packaged in this object. IOError, ZeroDivisionError, TypeError, SystemCallError, etc are examples of exceptions derived from class Exception. Ruby predefines a hierarchy of exceptions: see next slide.
  • 6. ‘Exception Handling in RUBY’ Exception Class Heirarchy Exception Class Heirarchy
  • 7. ‘Exception Handling in RUBY’ User Defined Exceptions User Defined Exceptions User-Defined Exception Users can create exception classes of their own. These must inherit from class StandardError or its children. If they dont, such exceptions will not be detected by default. They may include more specific information about the exception.
  • 8. ‘Exception Handling in RUBY’ User Defined Exceptions Handling Exceptions Handling Exceptions The basic approach to exception handling involves the use of: Enclose candidate code in begin/end block. Use rescue block to handle specific class of exceptions, where: Report the error, Code to handle detected error, Raise the exception using raise. Use ensure block to ensure execution of some essential code after handling, like deallocation of resources such as DB connections, etc. We can draw analogies to C++/Java exception handling: begin/end block for candidate code. (like try block) rescue blocks for handling code. (like catch blocks) raise command for raising the exception. (like throw) ensure command for necessary handling. (like final)
  • 9. ‘Exception Handling in RUBY’ User Defined Exceptions Handling Exceptions Example: Using rescue, raise and ensure
  • 10. ‘Exception Handling in RUBY’ User Defined Exceptions Handling Exceptions Handling Exceptions (continued..) Variables $ refers to the default global variable that stores the exception object for the exception. stderrobj is an example of user-defined variable storing the reference to the exception object. Matching exceptions to correct rescue block is like the case statement mechanism, object.kindof? result compared to exception types in rescue statements.
  • 11. ‘Exception Handling in RUBY’ User Defined Exceptions Raising Exceptions Raising Exceptions Raising exceptions deliberately in code help to trigger alerts where errors are expected and need to be handled. The raise statement can take the following forms: raise Raises current exception again, or RuntimeError if none. raise <message> Creates new RuntimeError exception, associates it with mentioned string, and raises the exception up the call stack. raise <exception class>, <message>, <call stack> Creates exception with arg-1 used as required exception type, arg-2 as message string, and arg-3 as stack trace.
  • 12. ‘Exception Handling in RUBY’ User Defined Exceptions Raising Exceptions Example: Typical Usage of raise
  • 13. ‘Exception Handling in RUBY’ User Defined Exceptions The Catch/Throw Clauses The catch/throw Clauses The rescue and raise mechanism is thus used for abandoning execution when unwanted errors occur. The catch and throw mechanism is used to continue execution at some point up the call stack. Working of catch/throw: catch defines a block with a specific label. The block is exeuted, typically accross nested functions, till a throw followed by the label is encountered. The call stack is then scoured for a catch block with a matching label. On a match, Ruby rolls back execution to the point and terminates the block. If the throw had an optional 2nd argument, it is returned as value of the catch block.
  • 14. ‘Exception Handling in RUBY’ User Defined Exceptions The Catch/Throw Clauses Example: Typical usage of catch/throw
  • 15. ‘Exception Handling in RUBY’ Conclusions Conclusions Exception Handling is essential for managing errors in object-oriented code. The Ruby Exception Handling mechanism includes: rescue and final clauses - for handling unwanted errors and exit gracefully. raise - for deliberately creating and raising exceptions in code. catch and throw clause - for continuing execution at some point up the function call stack.
  • 16. ‘Exception Handling in RUBY’ Conclusions References http://www.insula.cz/dali/material/rbycl/. http://www.ruby-lang.org/. Dave Thomas and Chad Fowler and Andy Hunt. Programming Ruby: The Pragmatic Programmers’ Guide. Pragmatic Bookshelf, Oct 2004.