CSC/ECE 517 Fall 2009/wiki1b 3 b4

From Expertiza_Wiki
Revision as of 08:06, 20 September 2009 by Zwang6 (talk | contribs)
Jump to navigation Jump to search

Exception-Handling in O-O language

Most major O-O language use the almost the same way to deal with exception occurred during runtime. The mechanism is: When an error occurs within a method, the method creates an object and hand 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 the error occurred. Creating an exception object and handing it to the runtime system is calling throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is knows as the call stack. The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handling mechanism of several major O-O languages are listed below with example provided.

Java

One of the most important concepts about Java exception handling to understand is that there are three general types of throwable classes: unchecked exceptions, checked exceptions.

Unchecked exception includes runtime exception and errors. Runtime exception are exceptional conditions that are internal to the application, and that are internal to the application, and that the application ususally cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. Errors are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction.

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. For checked exception, the Catch or Specify Requirement means that code that might throw certain exceptions must be enclosed by either of the following: A try statement that catches the exception. The try must provide a handler for the exception. A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception.

In detail to construct exception handler: The first step is to enclose the code that might throw an exception within a try block. In general, an exception handler block in Java looks like following.

try { exception could thrown from here }catch (ExceptionType name) {

}catch (ExceptionType name) { } finally {}

One or more catch blocks should be provided directly after try block. Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Smalltalk

Exception-handling in Smalltalk use almost same way as that in Java with only nuance differences. The primary difference is in how the context stack is handled. In Java, when you get to the handler code, the stack has been unwound and is just gone. But not so in Smalltalk, the stack is an argument held in the exception. In this manner, it is possible for system to return to the point where the exception got thrown, and simply proceed as if it hadn’t happen.

C++

Although Java’s exception handling is an adaption of C++ exception handling. Yet, there are some substantial differences between the two language in this regard.

1. Exception types

In Java, all exceptions are ultimately derived from a common base class. In C++, an exception needn't be derived from an exception class . In fact, a C++ exception can even be a built-in type as well, say int or char *:

try {//C++, not Java

     if (abnormal_state)
     throw "must quit!";

}

2. Exception Specification

Another difference between the two languages is that Java enforces exception specifications rigorously. That is, every method must specify which exceptions it might throw in an exception specification. In C++, however, exception specifications are optional and quite often are completely omitted.

3.Destructors vs. finally()

The crucial difference for our discussion isn't directly related to exceptions, but to the underlying object model of the two languages. In C++, there's symmetry between a constructor and a destructor. Usually, resources allocated during construction are released in the destructor. Because destructor execution in C++ is deterministic -- you know exactly when a destructor run -- you can be certain that resources will not leak or remain locked once an object has been destroyed. By contrast, Java has no destructors. The closest thing to this concept is the finalize() method which is called when the garbage collection reclaims the storage of an object. The problem is that you can't tell in advance when the garbage collector will run. In some cases, it may take days and weeks before the JVM invokes it; some programs even disable GC altogether. Consequently, resources released in finalize() might remain locked. Due to the lack of this constructor-destructor symmetry, Java programmers must use a different technique to ensure a prompt release of allocated resources. This is exactly where finally comes into the limelight. When an exception is thrown in a C++ program, the stack unwinding mechanism guarantees that destructors of auto objects have executed upon entering a matching handler. You can be sure that resources have been released, in any case. If an exception has occurred, the stack unwinding mechanism is responsible for invoking destructors and subsequently releasing resources; if no exception occurs, the destructor is called normally, upon leaving the block in which the object was defined. For example:

try {

std::string cat("Bustopher Jones");
if (error)
throw std::string ("Cat-astrophe!");

}//cat is destroyed here if no exception has occurred catch(std::string& exc) { //at this point, cat has been destroyed //during stack unwinding } In Java, things are different: try {//Java pseudo-code

myConnectionr connection= new myConnection (db_connection);
if (connection.fail())
//..throw an exception and leave this block

else //continue normally

connection.use();

} catch(Exception ex)//..handle the connection failure here { } finally {

connection.release(); 

}

First, you allocate a resource inside a try block. If an exception occurs, control is transferred to the catch() block. Releasing the resource inside a try-block is a bad idea, though, as the exception may have occurred even before connection was constructed. Secondly, if no exception has occurred, the release() call won't take place at all. Java designers decided to solve this problem by introducing a finally-block which executes regardless of the existence of an exception. In other words, a finally block is like a destructors in C++ -- its execution is guaranteed. As such, it's the proper place for safely releasing resources in Java. Evaluation The differences between the two languages suggest that finally is indispensable in Java, because this language doesn't implement the C++ stack unwinding model. The second and more important conclusion, is that finally() is completely unnecessary in C++. Using auto objects inside a try-block guarantees their destruction. Since objects' destructors run whether an exception has occurred or not, they are the proper place for releasing resources. The call for adding finally to C++ usually stems from inexperience in this language. For example, programmers who allocate objects dynamically in a try-block of Java: try{//poor programming style

std::string pstr=new std::string cat("Bustopher");
if (error)
 throw std::string ("Cat-astrophe!");

} They "need" a finally block where they can safely delete pstr. However, by replacing pstr with an auto std::string object, you avoid this hassle neatly. Furthermore, even if you must use a dynamically allocated object, you can always wrap it in an auto_ptr: try{

auto_ptr<string> pstr(new std::string ("Bustopher"));
if (error)
 throw std::string ("Cat-astrophe!");

}