Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

Exception Handling by q8a1ML


									            Exception Handling         1

• Introduction to Exception Handling
• Exception Handling in PLs
  – Ada
  – C++
  – Java
• Sebesta Chapter 14
            Why Exception Handling?                                      2

• No exception handling
   –   Unchecked errors abort the program
   –   Clutter program with if-clauses checking for errors
   –   Use the return value to indicate errors
   –   Pass an error-label parameter in all subprograms
   –   Pass an errors handling subprogram to all subprograms

• With exception handling
   – Programs can catch exceptions, handle the problems and continue
   – Programmers are encouraged to consider all possible errors
   – Exception propagation allows for reuse of exception handling code
                    Basic Concepts                                       3

• An exception
   – An exceptional state in program execution, typically an error

• Exception handling
   – Built-in mechanism for special flow control when exception occurs

• Exception handler
   – Code unit that handles an exception

• An exception is raised (or thrown)
   – When the associated exceptional event occurs
                     Design Issues                              4

•   How and where are exception handlers specified?
•   What is the scope of an exception handler?
•   How is an exception event bound to an exception handler?
•   Is the exception info available in the handler?
•   Where does control go at the end of an exception handler?
•   Is finalization supported?
•   Can user define her own exceptions and how?
•   Should there be default exception handlers?
•   Can built-in exceptions be explicitly raised?
•   Are hardware errors exceptions that can be handled?
•   Are there any built-in exceptions?
•   Can exceptions be disabled and how?
Exception Handling Control Flow   5
              Exception Handling in Ada                                6

• An exception handler is
   –   a subprogram body, or
   –   a package body, or
   –   a task, or
   –   a block

• Exception handlers do not have parameters
   – They are usually with the code where an exception can be raised

• Handlers are at the end of the block in which they occur
          Exception Handlers Syntax      7

• Handler form
     when exception { | exception } =>
     [when others =>

•   exception form
     exception_name | others
             Propagation of Exceptions                  8

• If exception is raised in a unit without a handler
  for that exception, the unit is terminated
• Then, the exception is propagated
   – From a procedure
      • to the caller
   – From a block
      • to parent scope
   – From a package body
      • to the declaration part of the declaring unit
   – In a task
      • No propagation, just mark it "Completed"

• If the unit where an exception is propagated to
  doesn't handle it, that unit is terminated, too
                       Other Syntax                            9

• User-defined exceptions form
     exception_name_list : exception;

• Raising exceptions form
     raise [exception_name]
   – If the exception name is omitted, the same exception is

• Exception conditions can be disabled with
     pragma SUPPRESS(exception_list)
               Predefined Exceptions                               10

  – index constraints, range constraints, etc.
  – illegal numeric operation (overflow, division by zero, etc.)
  – call to a subprogram whose body has not been elaborated
  – system heap overflow
  – Some tasks' error
   Evaluation of Ada's Exception Handling                11

• Reflects the state-of-the-art in PL design in 1980

• A significant advance over PL/1

• Ada was the only widely used language with exception
  handling before it was added to C++
           Exception Handling in C++        12

• Exception handling was added in 1990

• Design is based on CLU, Ada, and ML

• Syntax
    try {
      -- code that may raise an exception
    } catch (formal parameter) {
      -- handler code
    } catch (formal parameter) {
      -- handler code
                     catch Function                         13

• catch is an overloaded name of all handlers
   – The formal parameter of each catch must be unique
• The formal parameter doesn't need to be a variable
   – It can be a type name to distinguish it from others
• The formal parameter can supply the handler with
  information about the exception
• If the formal parameter is an ellipsis, it handles all
  exceptions not yet handled
• After a handler is executed, control flows to the first
  statement after the sequence of catches
• An unhandled exception is propagated to the caller
• The propagation continues to the main function
• If no handler is found, the default handler is called
                 Throwing Exceptions                      14

• Exceptions are raised explicitly by
     throw [expression];
• A throw with no operand re-raises the exception
   – It can only appear within a handler
• The type of the expression disambiguates the handlers
                Other Design Choices                      15

• All exceptions are user-defined

• Exceptions are neither specified nor declared

• The default handler unexpected terminates the program
   – unexpected can be redefined by the user

• A function can list the exceptions it may raise

• A function can raise any exception (the throw clause)
   – No specification is required
  Evaluation of Exception Handling in C++                             16

• Advanced compared to Ada

• However, some weird design choices

• Reliability
   – Hardware- and system software-exceptions can't be handled

• Readability
   – Exceptions are not named
   – Exceptions are bound to handlers via the type of the parameter
           Exception Handling in Java               17

• Based on that of C++

• More OOP-compliant

• All exceptions are objects of subclasses of the
  Throwable class
               Classes of Exceptions                 18

• Superclasse Throwable has two subclasses
• Error
  – System events such as heap overflow
  – User programs aren't required to handle these
  – Usually they don't handle them
• Exception
  – User-defined exceptions are usually subclasses
  – Has rich subtree of predefined subclasses
      • NullPointerException, IOException,
        ArrayIndexOutOfBoundsException, …
  • Typically, user programs must handle these
              Java Exception Handlers                             19

• try clause is exactly like in C++
• catch clause is like in C++
   – But every catch must have a declared named parameter whose
     type is a subclass of Throwable
• Exceptions are thrown as in C++ with throw, but an
  object must be thrown
   – It must bean instance of a subclass of Throwable
• An exception is bound to the 1st handler whose
  parameter type matches the thrown object
   – It has the same class or is a its superclass
• A handler that catches a Throwable parameter will
  catch all unhandled exceptions
   – This insures that all exceptions are caught
   – Of course, it must be the last in the try construct
               The finally Clause                           20

• Optional, at the end of a try-catch-catch construct

• Form
   finally {

• Specifies code that will be always executed, regardless
  of what happens in the try construct
             Example with finally                      21

• A try construct with a finally clause can be used
  outside exception handling context
    try {
      for (i = 0; i < 100; i++) {
        if (…) {return i;} // index found, return it
    } finally {
      … // clean up
                     Continuation                              22

• If no handler is found in the try construct, the search is
  continued in the nearest enclosing try construct, etc.

• If no handler is found in the method, the exception is
  propagated to the method’s caller

• If no handler is found (all the way to main), the program
  is terminated
    Checked and Unchecked Exceptions                            23

• The Java throws clause is different from C++

• Unchecked exceptions
   – Exceptions of class Error and RunTimeException and their
• Checked exceptions
   – All other exceptions
• A method that may throw a checked exception must
   – Either handle it, or
   – List it in the throws clause
• A method cannot declare more exceptions in its throws
  clause than the method it overrides
                    Handling Choices                                   24

• An exception can be
  – Caught and ignored
     • Usually a bad, bad choice
  – Caught and handled completely
  – Propagated
     • I.e. not caught
  – Caught, handled and re-thrown
     • By throwing it in the handler
  – Caught, handled, then a different exception is thrown
     • Often the best choice as system exceptions carry insufficient
                          Assertions                 25

• Statements in the program specifying whether the
  current state of the computation is as expected

• Must form a boolean expression that
   – When evaluated to true nothing happens
      • The program state is ok
   – When evaluated to false throws AssertionError

• Can be disabled during runtime without program
  modification or recompilation

• Two forms
   – assert condition;
   – assert condition: expression;
                        Evaluation                           26

• The types of exceptions makes more sense than in the
  case of C++
• The throws clause is better than that of C++
   – The throw clause in C++ says little to the programmer
• The finally clause is often useful
• The Java interpreter throws a variety of exceptions that
  can be handled by user programs

To top