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 ïŹle that doesnât exist is
acceptable in some circumstances and is a fatal error at other
times. What does the ïŹle-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 oïŹers 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 predeïŹnes a hierarchy of exceptions: see next slide.
7. âException Handling in RUBYâ
User DeïŹned Exceptions
User DeïŹned Exceptions
User-DeïŹned 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 speciïŹc information about the
exception.
8. âException Handling in RUBYâ
User DeïŹned 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 speciïŹc 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 DeïŹned Exceptions
Handling Exceptions
Example: Using rescue, raise and ensure
10. âException Handling in RUBYâ
User DeïŹned 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-deïŹned 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 DeïŹned 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 DeïŹned Exceptions
Raising Exceptions
Example: Typical Usage of raise
13. âException Handling in RUBYâ
User DeïŹned 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 deïŹnes a block with a speciïŹc 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 DeïŹned 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.