TerritorioPc


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 subroutine|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 if it 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)|crashing 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 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|Ada, C plus plus|C++, D programming language|D, Delphi_programming_language|Delphi, Objective-C, Java programming language|Java, Eiffel programming language|Eiffel, Ocaml, Python programming language|Python, Common Lisp, SML programming language|SML, PHP and all Microsoft .NET|.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)|stack of subroutine|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|C#

public static void Main()

C plus plus|C++

#include int main() In C++, a Resource Acquisition Is Initialization|resource acquisition is initialization technique can be used to clean up resources in exceptional situations.

D programming language|D

import std.stdio; // for writefln() int main() In D, a finally clause or the Resource Acquisition Is Initialization|resource acquisition is initialization technique can be used to clean up resources in exceptional situations.

Java programming language|Java

try catch (ExampleException ee) finally

Python programming language|Python

try: f = file("aFileName") except IOError: 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|OCaml

exception MyException of string
  • int (
  • exceptions can carry a value
  • ) let _ = try raise (MyException ("not enough food", 2)); print_endline "Not reached" with | MyException (s, i) -> Printf.printf "MyException: %s, %d\n" s i | _ -> (
  • catch all exceptions
  • ) print_endline "Unexpected exception"

    C programming language|C

    The most common way to implement exception handling in standard C is to use setjmp/longjmp functions: #include #include enum ; jmp_buf state; int main() Some operating systems also have similar features, for example Microsoft Windows has "structured exception handling": int filterExpression (EXCEPTION_POINTERS
  • ep) int main()

    Perl

    eval 
    if($@)
    

    PHP

    // Exception handling is only available in PHP versions 5 and greater.
    try  catch (FirstExceptionClass $exception)  catch (SecondExceptionClass $exception) 
    
    (php5powerprogramming: ISBN 0-13-147149-X, page 77)

    Delphi_programming_language|Delphi

    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 the set of exceptions which may arise when calling a method or function is part of the type of the function. For instance, in Java, 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, some implementations (e.g. Java) require them as a form of syntactic sugar|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. Other languages, such as OCaml, may take advantage of external exception checkers, both transparent (i.e. they do not require any syntactic annotations) and facultative (i.e. it is possible to compile and run a program without having checked the exceptions, although this is not suggested for production code).

    Implementation

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

    Condition systems

    Common Lisp, Dylan_programming_language|Dylan 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 '''resumption model''' of exception handling, in which some ''exceptions'' are said to be '''continuable''': it is permitted to return to the expression that signaled an exception, after having taken corrective action in the handler. The condition system is generalized thus: within the handler of a non-serious condition (a.k.a. ''continuable exception''), it is possible to jump to predefined restart points (a.k.a. ''restart|restarts'') 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|mechanisms'' 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 by Gunjan Doshi
  • Article "http://java.sun.com/developer/technicalArticles/Programming/exceptions2/index.html by Brian Goetz
  • Article "http://oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html by Kyle Loudon
  • Article "http://perl.com/pub/a/2002/11/14/exception.html by Arun Udaya Shankar
  • Article "http://intel.com/cd/ids/developer/asmo-na/eng/81438.htm
  • Article "http://codeproject.com/cpp/exceptionhandler.asp by Vishal Kochhar
  • Article "http://codeproject.com/cpp/exception.asp by Konstantin Boukreev
  • Article "http://codeproject.com/dotnet/ExceptionHandling.asp
  • Article "http://www.on-time.com/ddj0011.htm by Tom Schotland and Peter Petersen
  • Article "http://www.andreashalter.ch/phpug/20040115/ by Andreas Halter
  • Article "http://www.gamedev.net/reference/programming/features/sehbasics/ by Vadim Kokielov
  • Paper "http://www.informatik.uni-hamburg.de/TGI/pnbib/f/faustmann_g1.html by Gert Faustmann and Dietmar Wikarski
  • Paper "http://www.ssw.uni-linz.ac.at/Research/Papers/Hof97b.html
  • http://www.object-arts.com/EducationCentre/Overviews/ExceptionHandling.htm
  • http://c2.com/cgi/wiki?CategoryException
  • http://citeseer.ifi.unizh.ch/cis?q=exception+handling
  • http://www.microsoft.com/msj/0197/exception/exception.aspx- Microsoft Systems Journal (1997)
  • http://artima.com/intv/handcuffsP.html- a conversation with Anders Hejlsberg
  • http://www.mindview.net/Etc/Discussions/CheckedExceptions


  • territoriopc.com // página bajo licencia GNU obtenida de wikipedia