CSC/ECE 517 Fall 2009/wiki1b 3 b4

From Expertiza_Wiki
Revision as of 08:16, 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!");

}

Objective C

There are two types of handle exceptions method in Objective C, the first one is using compiler directives. The second one is, for appropriate projects, the legacy mechanism of exception-handling macros.

Handling Exceptions Using Compiler Directives The compiler support for exceptions is based on four compiler directives: @try —Defines a block of code that is an exception handling domain: code that can potentially throw an exception. @catch() —Defines a block containing code for handling the exception thrown in the @try block. The parameter of @catch is the exception object thrown locally; this is usually an NSException object, but can be other types of objects, such as NSString objects. @finally — Defines a block of related code that is subsequently executed whether an exception is thrown or not. @throw — Throws an exception; this directive is almost identical in behavior to the raise method of NSException. You usually throw NSException objects, but are not limited to them.

As similar feature as Java, Objective C exception handling has to use finally block to do some cleanup, release resource work because of lack of automatic destructing objects.

And Although you can throw and catch objects other than NSException objects, the Cocoa frameworks themselves might only catch NSException objects for some conditions. So if you throw other types of objects, the Cocoa handlers for that exception might not run, with undefined results. (Conversely, non-NSException objects that you throw could be caught by some Cocoa handlers.) For these reasons, it is recommended that you throw NSException objects only, while being prepared to catch exception objects of all types..

Handling Exceptions Using Macros An exception handler is contained within a control structure created by the macros NS_DURING, NS_HANDLER, and NS_ENDHANDLER as shown below SomeMethod { ... NS_DURING ... if(/”error”/) { [anException raise]; } ... NS_HANDLER ... NS_ENDHANLER ... return; }


The section of code between NS_DURING and NS_HANDLER is the exception handling domain; the section between NS_HANDLER and NS_ENDHANDLER is the local exception handler. The code within the local exception handler is executed only if an exception is raised. Sending a raise message to an exception object causes program control to jump to the first executable line following NS_HANDLER.

Perl 5 First Perl has a built-in exception handling mechanism, a.k.a the eval{} block which does behavior like normal O-O language exception handling. It is implemented by wrapping the code that needs to be executed around an eval block and the $@ variable is checked to see if an exception occurred. To overcome the drawbacks of eval{} construct, Perl provides Error.pm module to implement O-O exception handling. It mimics the try/catch.throw syntax and provides two interfaces: 1. Procedural interface for exception handling (exception handling constructs) Base class for other exception classes. Perl exception handling is order of catch blocks matter. This means that the order of exception handlers is important. It's all the more critical if you have handlers at different levels in the inheritance hierarchy. Exception handlers that are built to handle exception types that are furthermost from the root of the hierarchy (Error) should be placed first in the list of catch blocks. An exception handler designed to handle a specific type of object may be pre-empted by another handler whose exception type is a superclass of that type. This happens if the exception handler for that exception type appears earlier in the list of exception handlers. Python In Python, Handling exception use similar methodology with a bit different directives names. They are try; except, finally, raise. Except is counterpart of Catch in the other O-O languages and raise is throw’s counterpart. The way of implementing finally clause in Python is different from that of most of the other O-O languages. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement. Besides, Python has a unique directive in exception handling, that is else block. It is an optional clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

Ruby In Ruby exception handling, there is no try clause. The code which might throw exception is wrapped in begin end block. And rescue block acts as catch clause in Java, it tells Ruby the expecting exception class, and build exception handler. You can have multiple rescue clauses in a begin block, and each rescue clause can specify multiple exceptions to catch. The processing Ruby decide which rescue clause to execute is pretty similar to that used by the case statement. For each rescue clause in the begin block, Ruby compares the raised exception against each of the parameters in turn. If the raised exception matches a parameter, Ruby executes the body of the rescue and stops looking, matching will succeed if the parameter has the same class as the exception or is an ancestor of the exception. So order of rescue is matter either. If you write a rescue clause with no parameter list, the parameter defaults to StandardError. If no rescue clause matches, or if an exception is raised outside a begin/end block, Ruby moves up the stack and looks for an exception handler in the caller, then in the caller's caller, and so on. Although the parameters to the rescue clause are typically the names of Exception classes, they can actually be arbitrary expressions (including method calls) that return an Exception class. Ruby accomplish tidying up things by ensure which is similar to finally block in Java. Ruby also has else clause which is similar to ensure, but less useful, construct. If present, it goes after the rescue clauses and before any ensure. The body of an else clause is executed only if no exceptions are raised by the main body of code. Ruby also has retry clause which enable system to repeat the entire begin/end block. This is useful sometimes you may be able to correct the cause of exception. But clearly there is tremendous scope for infinite loop, so this is a feature to use with caution. To throw an exception in Ruby, it uses raise clause instead of throw clause in Java.


C# C# also provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process. But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.  

If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.  

In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.