Google
 
   
Login
Username:

Password:


Lost Password?

Register now!
Search
Main Menu
top books
Polls
What do you think about php-deluxe.net?
Excellent!
Cool
Hmm..not bad
What the hell is this?
encyclopedia
recommendation
compare webbrowser
Freenet DSL
Who's Online
11 user(s) are online (11 user(s) are browsing encyclopedia)

Members: 0
Guests: 11

more...
browser tip
Unix Befehle
manual of unix befehle
recommendation!
Sponsored
partner

Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle runtime errors or other problems ( exceptions ) which occur during the execution of a computer program.

In general, current state will be saved in a predefined location and execution will switch to a predefined handler. Depending on the situation, the handler may later resume the execution at the original location, using the saved information to restore the original state. An exception which will be usually resumed is a page fault, while a division by zero usually cannot be resolved transparently.

From the processing point of view, hardware Interrupts are similar to resumable exceptions, except they are usually not related to the current program flow.

= Goals of exceptions =

Exception handling is intended to facilitate use of reasonable mechanisms for handling erroneous or exceptional situations that arise in programs. Exception handling can be used to pass information about error situations that occur within library code to its users, and selectively respond to those errors.

A possible role of exception handling is to allow the program to continue its normal operation and prevent Crash (computing) and displaying of cryptic error messages to the user. In many cases, it is sufficient to stop the program and produce an error report; the difference with systems that do not use exceptions to signal improper program executions is that with proper exception handling, the erroneous condition may be pointed precisely, whereas otherwise it is often detected later, making Debugging difficult.

Exception handling makes the signal (computing)-handling technique used in other languages obsolete.

= Exception safety =

A piece of code is said to be exception-safe if run-time failures within the code will not produce ill-effects, such as memory leaks, garbled data or invalid output. Exception-safe code must satisfy invariants placed on the code even if exceptions occur. There are several levels of exception safety: # failure transparency, operations are guaranteed to succeed and satisfy all requirements even in presence of exceptional situations. (best) # commit or rollback semantics, operations can fail, but failed operations are guaranteed to have no side effects. # basic exception safety, partial execution of failed operations can cause side effects, but invariants on the state are preserved (that is, any stored data will contain valid values). # minimal exception safety, partial execution of failed operations may store invalid data but will not cause a crash. # no exception safety, no guarantees are made. (worst)

Usually at least basic exception safety is required. Failure transparency is difficult to implement, and is usually not possible in libraries where complete knowledge of the application is not available.

= Exception support in programming languages =

Certain computer languages such as Ada programming language, C plus plus, D programming language, Delphi_programming_language Objective-C, Java programming language, Eiffel programming language, Ocaml, Python programming language, Common Lisp, SML programming language, PHP and all Microsoft .NET CLS-compliant languages have built-in support for exceptions and exception handling. In those languages, the advent of an exception (more precisely, an exception handled by the language) unwinds the Stack (computing) of function calls until an exception handler is found. That is, if function f has a handler H for exception E , calls function g , which in turn calls function h , and an exception E occurs in h , then functions f and g will be terminated and H will handle E .

== Csharp ==

public static void Main() { try { // Code that could throw an exception } catch(System.Net.WebException exp) { //Process a WebException } catch(System.Exception) { //Process a System level CLR exception, that is not a System.Net.WebException //since the exception has not been given an identifier it cannot be referenced } catch { //Process a non-CLR exception } finally { // (optional) code that will *always* execute } }

== C plus plus ==

#include int main() { try { // do something (might throw an exception) } catch (const std::exception& e) { // handle exception e } catch (...) { // unknown exception, should not happen } }

In C++, a Resource Acquisition Is Initialization technique can be used to clean up resources in exceptional situations.

== Java programming language ==

try { // Normal execution path } catch (ExampleException ee) { // Control jumps here if ExampleException or any of its subclasses happen } catch (Throwable t) { // Throwable is the superclass of all exception classes, so this is equivalent to C++ s catch (...) } finally { // This optional section is executed upon termination of any of the try or catch blocks above }

==Python programming language==

try: f = file( aFileName ) except EnvironmentError: print Unable to open file except: # catch all exceptions print Unexpected error else: # no exception was raised try: f.write(could_make_error()) finally: # clean-up actions f.close()

==Objective CAML==

exception MyException of string * int (* exceptions have types *) let _ = try raise (MyException ( not enough food , 2)); print_endline Not reached with | MyException (s, i) -> Printf.printf %s: %d s i | _ -> (* catch all exceptions *) print_endline Unexpected exception

==C programming language==

The most common way to implement exception handling in standard C is to use setjmp/longjmp functions:

#include #include enum { SOME_EXCEPTION = 1 }; jmp_buf state; int main(){ int exception; if == 0){ // try if(/* something happend */) longjmp(state, SOME_EXCEPTION); // throw SOME_EXCEPTION } else switch(exception){ case SOME_EXCEPTION: // catch SOME_EXCEPTION puts( SOME_EXCEPTION catched ); break; default: // catch ... puts( Some strange exception ); } return 0; }

Some operating systems also have similar features, for example Microsoft Windows has structured exception handling :

int filterExpression (EXCEPTION_POINTERS* ep) { ++ep->ContextRecord->Eip; return EXCEPTION_CONTINUE_EXECUTION; } int main() { static int zero; __try { zero = 1/zero; printf ( Past the exception. ); } __except (filterExpression (GetExceptionInformation())) { printf ( Handler called. ); } return 0; }

== Perl ==

eval { ... // Code that could throw an exception } if($@){ # print some statements here or redirect the page somehwre else } else { # do nothing }

== PHP ==

// Exception handling is only available in PHP versions 5 and greater. try { ... // Code which might throw an exception } catch (FirstExceptionClass $exception) { ... // Code which handles this exception } catch (SecondExceptionClass $exception) { }

(php5powerprogramming: ISBN 0-13-147149-X, page 77)

== Delphi_programming_language ==

try try // Code which may raise an exception except on E:Exception do // Code to call when an exception is raised end; finally // Code which will be executed whether or not an exception is raised (e.g. clean-up code) end;

= Checked exceptions =

A language is said to have checked exceptions when it requires each method or function to declare the types of exceptions that may arise when calling it. For example, if a method is capable of throwing a FooException, it must declare this fact in its method header. Failure to do so raises a compiler error.

== Pros and cons ==

Checked exceptions can, at compile time, greatly reduce (but not entirely eliminate) the incidence of unhandled exceptions surfacing at runtime in a given application. However, they are a form of syntactic salt that some see as a nuisance, either requiring large throws declarations (in the case of Java), or encouraging the (ab)use of poorly-considered try/catch blocks that can potentially hide legitimate exceptions from their appropriate handlers.

== Implementation ==

Checked exceptions currently exist in Java, but not in C++, C#, or Python.

== See also ==

  • [http://artima.com/intv/handcuffsP.html The Trouble with Checked Exceptions] - a conversation with Anders Hejlsberg
  • [http://www.mindview.net/Etc/Discussions/CheckedExceptions Does Java Need Checked Exceptions]
  • = Condition systems =

    Common Lisp, Dylan_programming_language and Smalltalk have a Condition system which encompasses the aforementioned exception handling systems. In those languages or environments the advent of a condition (a generalisation of an error according to Kent Pitman) implies a function call, and only late in the exception handler the decision to unwind the stack may be taken.

    Conditions are a generalization of exceptions. When a condition arises, an appropriate condition handler is searched for and selected, in stack order, to handle the condition. Conditions which do not represent errors may safely go unhandled entirely; their only purpose may be to propagate hints or warnings toward the user. [http://www.franz.com/support/documentation/6.2/ansicl/section/conditio.htm]

    This is related to the so-called ) that lie between the signaling expression and the condition handler. Restarts are functions closed over some lexical environment, allowing the programmer to repair this environment before exiting the condition handler completely or unwinding the stack even partially.

    == Separating mechanism from policy ==

    Condition handling moreover provides a separation of mechanism from policy. Restarts provide various possible mechanisms for recovering from error, but do not select which mechanism is appropriate in a given situation. That is the province of the condition handler, which (since it is located in higher-level code) has accessible to it a broader view.

    An example: Suppose there is a library function whose purpose is to parse a single Syslog file entry. What should this function do if the entry is malformed There is no one right answer, because the same library could be deployed in programs for many different purposes. In an interactive log-file browser, the right thing to do might be to return the entry unparsed, so the user can see it -- but in an automated log-summarizing program, the right thing to do might be to supply null values for the unreadable fields, but abort with an error if too many entries have been malformed.

    That is to say, the question can only be answered in terms of the broader goals of the program, which are not known to the general-purpose library function. Nonetheless, exiting with an error message is only rarely the right answer. So instead of simply exiting with an error, the function may establish restarts offering various ways to continue -- for instance, to skip the log entry, to supply default or null values for the unreadable fields, to ask the user for the missing values, or to unwind the stack and abort processing with an error message. The restarts offered constitute the mechanism available for recovering from error; the selection of restart by the condition handler supplies the policy .

    == See also == *Triple fault

    =External links=

    *Article [http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html Best Practices for Exception Handling] by Gunjan Doshi *Article [http://java.sun.com/developer/technicalArticles/Programming/exceptions2/index.html Exceptional practices] by Brian Goetz *Article [http://oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html Programming with Exceptions in C++] by Kyle Loudon *Article [http://perl.com/pub/a/2002/11/14/exception.html Object Oriented Exception Handling in Perl] by Arun Udaya Shankar *Article [http://intel.com/cd/ids/developer/asmo-na/eng/81438.htm How to Implement Software Exception Handling] *Article [http://codeproject.com/cpp/exceptionhandler.asp How a C++ compiler implements exception handling] by Vishal Kochhar *Article [http://codeproject.com/cpp/exception.asp Several classes for exception handling] by Konstantin Boukreev *Article [http://codeproject.com/dotnet/ExceptionHandling.asp User Friendly Exception Handling] *Article [http://www.on-time.com/ddj0011.htm Exception Handling in C without C++] by Tom Schotland and Peter Petersen *Article [http://www.andreashalter.ch/phpug/20040115/ What are Exceptions - The Concept] by Andreas Halter *Article [http://www.gamedev.net/reference/programming/features/sehbasics/ Structured Exception Handling Basics] by Vadim Kokielov *Paper [http://www.informatik.uni-hamburg.de/TGI/pnbib/f/faustmann_g1.html Exception Handling in Petri-Net-based Workflow Management] by Gert Faustmann and Dietmar Wikarski *Paper [http://www.ssw.uni-linz.ac.at/Research/Papers/Hof97b.html Zero-Overhead Exception Handling Using Metaprogramming] *[http://www.object-arts.com/EducationCentre/Overviews/ExceptionHandling.htm Overview for Smalltalk] *[http://c2.com/cgi/wikiCategoryException Descriptions from Portland Pattern Repository] *[http://citeseer.ifi.unizh.ch/cisq=exception+handling Citations by CiteSeer] *[http://www.microsoft.com/msj/0197/exception/exception.aspx A Crash Course on the Depths of Win32 Structured Exception Handling] - Microsoft Systems Journal (1997)