CSC/ECE 517 Fall 2009/wiki1b 3 NCS: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(32 intermediate revisions by the same user not shown)
Line 3: Line 3:
An exception is an abnormal event, which occurs during the execution of a program that interrupts the normal flow of the program. [http://en.wikipedia.org/wiki/Exception_handling Exception handling] is the programming constructs a language provides to handle exceptions.  
An exception is an abnormal event, which occurs during the execution of a program that interrupts the normal flow of the program. [http://en.wikipedia.org/wiki/Exception_handling Exception handling] is the programming constructs a language provides to handle exceptions.  


We will cover exception handling goals and characteristics for Object Oriented languages in general and will go over a concrete example for exception handling in JAVA language.
== Programming Constructs for exception handling ==
== Goals for a well designed exception handling system
*Improves software reliability
*readability
*usability
*easier debugging and maintainability.


A typical exception handling flow in most programming languages flows something like
Exception handling systems in general strive to improve software reliability, readability, usability, maintainability and easier debugging.  
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when and where the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.


Most Object Oriented languages with the exception of Smalltalk* have exception handling systems that provide constructs to the programmer to
Most modern Object Oriented Language exception handling systems provide the programmers a means to
=== Raising an exception ===
When an error occurs within a method, the method creates an object and hands it off to the runtime system. Creating an exception object and handing it to the run time system is called throwing an exception. This done typically using either a throw or raise statement. This statement takes the exception object as an argument.


- Raising an exception.
=== Create Exception Objects ===
Most programming languages provide a statement (throw/raise) to initiate an exception.
The Exception Object typically contains the following information about the error
* Type of error
* State of the program
* Where the error occurred


- Exception handlers
Object Oriented languages also allow the programmer to organize the exceptions objects in an inheritance hierarchy allowing the sharing of common behaviors and actions for a set of exceptions.
Most Object Oriented languages provide a means to write exception handling blocks (catch/rescue/except) and also a means to specify the scope of the handlers (try block)


- Match Exceptions with exceptions handlers
=== Write Exception handlers ===
Provide a stack of handlers that can be traversed to match an exception with an appropriate handler
Exception handlers are generally written as blocks of code ( catch/rescue/except blocks ) that can specify the types of exceptions they can handle along with a means to specify the scope of the handler ( try block ). Multiple exceptions can be caught with a single handler.


- Exception Objects
Using the above statements a programmer can specify a stack of handlers that can be traversed to match an exception with an appropriate handler
Provide infrastructure to communicate exceptions from the methods where it occurs to the exception handlers.
Provide a mechanism to pass objects from the exception raiser to handler.


- Exception handler options
=== Match Exceptions with exceptions handlers ===
- Provide the handler means to either resume/retry/terminate the program or propagate the same or a new exception. Possibly spawn a debug process
Once an exception is raised the run time system will traverse the stack backwards to find an exception handler that can handle the raised exception. Once a handler is found that can handle the raised exception the run time system passes control to the handler along with the exception object.


- Allows exceptions to be organized in an inheritance hierarchy allowing sharing common behaviors and actions for a set of exceptions.
=== Handling Exceptions ===
The exception handler routine can look at the exception caught and may decide to perform one of the following actions
* Resume the program or retry the failed operation
* Propagate the exception
* Terminate the program
* Spawn a debug process


- Allow trapping multiple exceptions with a single handler.


== Example: Exception handling in JAVA ==
=== Exception hierarchy ===
All Exception objects in JAVA are sub classed from the Exception Object. <br>
http://www.artima.com/designtechniques/images/exceptFig1.gif


Example
Exception handling in JAVA


Specifying Exception handlers
* Checked vs Unchecked Exceptions
Try catch and finally blocks
Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown. Unchecked exceptions extend the java.lang.RuntimeException. [http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html Checked vs Unchecked] the Controversy.


The first step for writing exception handlers is to specify the scope of the handler using a try block. the try block encloses the code that can throw exceptions that the exception handler plans on handling. The exception handler itself is specified within the catch block. Each catch block handles the type of exception as specified by the argument of the catch block.  Finally the finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. The finally block also serves the purpose of avoiding bypassing the clean up code accidentally in the case of an exception or accidentally by a return or a break statement.
* Errors
Errors are hard errors within the JVM. Applications typically do not handle or throw Errors. Errors are unchecked exceptions.  
Example NullPointerException.


  try {
=== Throwing an Exception ===
// code  
The throw statement is used to throw an exception. The throw statement requires a single argument: a throwable object. Here's an example of a throw statement.
    } catch (ArrayIndexOutOfBoundsException e) {
// handler for ArrayIndexOutOfBoundsException
    } catch (IOException e) {
//handler for IO exception
    } finally {
// clean up
    }
 
Throwing an Exception
The throw statement is used to throw an exception. The throw statement requires a single argument: a throwable object. (subclass of the Throwable class). Here's an example of a throw statement.


<code>
     throw someThrowableObject;
     throw someThrowableObject;
</code>


Specifying exceptions thrown by an Method
Specifying exceptions thrown by an Method


public void foo() throws IOException,
<code>
                              ArrayIndexOutOfBoundsException {
    public void foo() throws IOException,  
}
          ArrayIndexOutOfBoundsException {
    }
</code>


=== Propagating an exception ===
You don't have to catch exceptions thrown from other methods. If you cannot do anything about the exception where the method throwing it is called, you can just let the method propagate the exception up the call stack to the method that called this method. If you do so the method calling the method that throws the exception must also declare to throw the exception.


You can also catch the exception and throw a new exception that the calling layer can understand and recover from. 


Types of exceptions
<code>
All exceptions that can be thrown are subclassed from Throwable class
  void updateNameInDBFile(String Name) throws IOException {
    % Performs some file IO operation and propagates the IOException to calling function
  }


Object
  ...
    |
Throwable
    |
__________________________________


| |
  try {
Error Exception
    % code calling updateNameInDBFile
... |
  } catch (IOException e) {
___________________
    throw new NameNotUpdatedException(e); // maps IOException to NameNotUpdatedException
| |
  }
...... RunTimeException
</code>
.....


=== Try catch and finally blocks ===


Errors are hard errors within the JVM. Applications typically do not handle or throw Errors
The first step for writing exception handlers is to specify the scope of the handler using a try block. the try block encloses the code that can throw exceptions that the exception handler plans on handling. The exception handler itself is specified within the catch block. Each catch block handles the type of exception as specified by the argument of the catch block.  Finally the finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. The finally block also serves the purpose of avoiding bypassing the clean up code accidentally in the case of an exception or accidentally by a return or a break statement.
 
<code>
Exceptions - Checked vs Unchecked.
  try
 
  {
Checked exceptions - all exceptions that must be specified and caught
    % code that might throw an exception
Unchecked exceptions - subclasses of RunTimeException calss these do need to be specified or caught
  }
  catch (SomeException se)
  {
    % code that handles this exception
  }
  catch (SomeOtherException soe)
  { 
    % code that handles this exception
  }
  finally  % optional block
  {
    % This code will always get executed
  }
</code>




* Small talk allows exception handlers to be only associated with classes and when an exception is raised it searches for the handler in the class where the exception was raised.
==References==
[http://portal.acm.org/citation.cfm?id=130948] Exception handling in Object Oriented Systems


http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
[http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html ]Sun Java Tutorial

Latest revision as of 15:30, 20 September 2009

Exception handling in Object Oriented Languages

An exception is an abnormal event, which occurs during the execution of a program that interrupts the normal flow of the program. Exception handling is the programming constructs a language provides to handle exceptions.

Programming Constructs for exception handling

Exception handling systems in general strive to improve software reliability, readability, usability, maintainability and easier debugging.

Most modern Object Oriented Language exception handling systems provide the programmers a means to

Raising an exception

When an error occurs within a method, the method creates an object and hands it off to the runtime system. Creating an exception object and handing it to the run time system is called throwing an exception. This done typically using either a throw or raise statement. This statement takes the exception object as an argument.

Create Exception Objects

The Exception Object typically contains the following information about the error

  • Type of error
  • State of the program
  • Where the error occurred

Object Oriented languages also allow the programmer to organize the exceptions objects in an inheritance hierarchy allowing the sharing of common behaviors and actions for a set of exceptions.

Write Exception handlers

Exception handlers are generally written as blocks of code ( catch/rescue/except blocks ) that can specify the types of exceptions they can handle along with a means to specify the scope of the handler ( try block ). Multiple exceptions can be caught with a single handler.

Using the above statements a programmer can specify a stack of handlers that can be traversed to match an exception with an appropriate handler

Match Exceptions with exceptions handlers

Once an exception is raised the run time system will traverse the stack backwards to find an exception handler that can handle the raised exception. Once a handler is found that can handle the raised exception the run time system passes control to the handler along with the exception object.

Handling Exceptions

The exception handler routine can look at the exception caught and may decide to perform one of the following actions

  • Resume the program or retry the failed operation
  • Propagate the exception
  • Terminate the program
  • Spawn a debug process


Example: Exception handling in JAVA

Exception hierarchy

All Exception objects in JAVA are sub classed from the Exception Object.
http://www.artima.com/designtechniques/images/exceptFig1.gif


  • Checked vs Unchecked Exceptions

Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown. Unchecked exceptions extend the java.lang.RuntimeException. Checked vs Unchecked the Controversy.

  • Errors

Errors are hard errors within the JVM. Applications typically do not handle or throw Errors. Errors are unchecked exceptions. Example NullPointerException.

Throwing an Exception

The throw statement is used to throw an exception. The throw statement requires a single argument: a throwable object. Here's an example of a throw statement.

   throw someThrowableObject;

Specifying exceptions thrown by an Method

   public void foo() throws IOException, 
         ArrayIndexOutOfBoundsException {
   }

Propagating an exception

You don't have to catch exceptions thrown from other methods. If you cannot do anything about the exception where the method throwing it is called, you can just let the method propagate the exception up the call stack to the method that called this method. If you do so the method calling the method that throws the exception must also declare to throw the exception.

You can also catch the exception and throw a new exception that the calling layer can understand and recover from.

 void updateNameInDBFile(String Name) throws IOException {
    % Performs some file IO operation and propagates the IOException to calling function
 }
 ...
 try {
    % code calling updateNameInDBFile
 } catch (IOException e) {
   throw new NameNotUpdatedException(e); // maps IOException to NameNotUpdatedException
 }

Try catch and finally blocks

The first step for writing exception handlers is to specify the scope of the handler using a try block. the try block encloses the code that can throw exceptions that the exception handler plans on handling. The exception handler itself is specified within the catch block. Each catch block handles the type of exception as specified by the argument of the catch block. Finally the finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. The finally block also serves the purpose of avoiding bypassing the clean up code accidentally in the case of an exception or accidentally by a return or a break statement.

 try 
 {
    % code that might throw an exception
 }
 catch (SomeException se) 
 { 
    % code that handles this exception
 }
 catch (SomeOtherException soe)
 {  
    % code that handles this exception
 }
 finally   % optional block
 {
    % This code will always get executed
 }


References

[1] Exception handling in Object Oriented Systems

[2]Sun Java Tutorial