FACTOID # 21: 15% of Army recruits from South Dakota are Native American, which is roughly the same percentage for female Army recruits in the state.
 
 Home   Encyclopedia   Statistics   States A-Z   Flags   Maps   FAQ   About 
   
 
WHAT'S NEW
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. The condition is called an exception. Alternative concepts are signal and event handler. Computer code (HTML with JavaScript) in a tool that uses syntax highlighting (colors) to help the developer see the purpose of each piece of code. ... Computer hardware is the physical part of a computer, including the digital circuitry, as distinguished from the computer software that executes within the hardware. ... A signal is an asynchronous event transmitted between one process and another. ... An event handler is a part of a computer program created to tell the program how to act in response to a specific event (e. ...


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. For example, an exception which will usually be resumed is a page fault, while a division by zero usually cannot be resolved transparently. In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ... In computer storage technology, a page fault is an interrupt (or exception) to the software raised by the hardware, when a program accesses a page that is not mapped in physical memory. ... In mathematics, a division is called a division by zero if the divisor is zero. ...


From the processing point of view, hardware interrupts are similar to resumable exceptions, except they are usually not related to the current program flow. In computer science, an interrupt is an asynchronous signal from hardware or software indicating the need for attention. ...

Contents


Exception conditions

Traditionally the term exception has been applied to a condition that is detected in hardware (e.g., when the value of the denominator in a divide instruction is zero many processors will generate (raise) an exception), however modern programming languages (e.g., Ada, C++, Java) use this term to describe a language construct that allows exceptions to be raised under software control. In algebra, a vulgar fraction consists of one integer divided by a non-zero integer. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... For a WikiBook on programming with C++, see Wikibooks: C++ Programming. ... Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ...


Exceptions are often raised in situations where some kind of error state has been reached (i.e., an exceptional condition). There are some people who believe that exceptions should only be used for handling errors. However, there are some problems where the use of exceptions can dramatically simplify the algorithm used and some people regard exceptions as just another coding construct that can be applied to help solve a problem.


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. Exceptions help the programmer avoid the semipredicate problem by freeing the return value of a function from the need to encode errors. In computer programming, a semipredicate problem occurs when a subroutine intended to return a useful value can fail, but the signalling of failure uses a otherwise valid return value. ...


A possible role of exception handling is to allow the program to continue its normal operation and prevent 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. A crash in computing is a condition where a program (either an application or part of the operating system) stops performing its expected function and also stops responding to other parts of the system. ... Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware thus making it behave as expected. ...


Exceptions vs. Return Value

An alternate form of error handling is to use the return value of a function to indicate that an error has occurred (this is similar in that "Return" is a unstructured construct: you can return from any point in the code, without processing the remainder). The main problems with return value error handling are:

  • Intermediate functions must check for error conditions, and pass it up if they cannot deal with it. This is:
    • fragile, as an error that is not checked for by an intermediate function is silently dropped
    • verbose, as every function call must be checked and handled individually
  • The semipredicate problem, namely that some (potentially valid) values are instead used as errors

In computer programming, a semipredicate problem occurs when a subroutine intended to return a useful value can fail, but the signalling of failure uses a otherwise valid return value. ...

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: A memory leak is a particular kind of unnecessary memory consumption by a computer program, where the program fails to release memory that is no longer needed. ... Invariant may have meanings invariant (computer science), such as a combination of variables not altered in a loop invariant (mathematics), something unaltered by a transformation invariant (music) invariant (physics) conserved by system symmetry This is a disambiguation page — a navigational aid which lists other pages that might otherwise share the...

  1. failure transparency, operations are guaranteed to succeed and satisfy all requirements even in presence of exceptional situations. (best)
  2. commit or rollback semantics, operations can fail, but failed operations are guaranteed to have no side effects.
  3. 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).
  4. minimal exception safety, partial execution of failed operations may store invalid data but will not cause a crash.
  5. 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, C++, Common Lisp, Corn, D, Delphi, Eiffel, Java, Objective-C, Ocaml, PHP (as of version 5), Python, REALbasic, Seed7, SML and all .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 of function calls until an exception handler is found. That is, if function f contains a handler H for exception E, calls function g, which in turn calls function h, and an exception E occurs in h, then functions h and g will be terminated and H in f will handle E. Exception handling syntax varies between programming languages to accomodate their overall syntax. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... For a WikiBook on programming with C++, see Wikibooks: C++ Programming. ... Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, standardised by ANSI X3. ... D is an object-oriented, imperative systems programming language designed by Walter Bright of Digital Mars as a successor to C++. He has done this by adding some features and reducing the complexity of C++ syntax. ... Delphi is the primary programming language of Borland Delphi. ... Eiffel is an object-oriented programming language which emphasizes the production of robust software. ... Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ... Objective-C, often referred to as ObjC or more seldomly as Objective C or Obj-C, is an object oriented programming language implemented as an extension to C. It is used primarily on Mac OS X and GNUstep, two environments based on the OpenStep standard, and is the primary language... Objective Caml (OCaml) is a general-purpose programming language descended from the ML family, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996. ... PHP is an open-source, reflective programming language used mainly for producing dynamic web content and server-side applications. ... Python is an interpreted programming language created by Guido van Rossum in 1990. ... REALbasic (RB) is an object-oriented dialect of the BASIC programming language developed and commercially marketed by REAL Software, Inc in Austin, Texas for Mac OS X, Microsoft Windows, and Linux. ... Seed7 is a general-purpose programming language designed by Thomas Mertes. ... SML (Standard ML) is a general-purpose, modular, functional programming language with compile-time type checking and type inference. ... The Microsoft . ... In computer science, a call stack is a special stack which stores information about the active subroutines of a computer program. ...


Excluding minor syntactic differences, there are only a couple of exception handling styles in use. In the most popular style, an exception is initiated by a special statement (throw, or raise) with an exception object. The scope for exception handlers starts with a marker clause (try, or the language's block starter such as begin) and ends in the start of the first handler clause (catch, except, rescue). Several handler clauses can follow, and each can specify which exception classes it handles and what name it uses for the exception object.


A few languages also permit a clause (else) that is used in case no exception occurred before the end of the handler's scope was reached. More common is a related clause (finally, or ensure) that is used whether an exception occurred or not. Notably, C++ lacks this clause and the Resource Acquisition Is Initialization technique is used instead. Resource Acquisition Is Initialization (often referred to by the acronym RAII; sometimes also used as Resource Initialization Is Acquisition or as the acronym RIIA) is a popular programming technique in C++ and D. The technique combines acquisition and release of resources with initialization and uninitialization of variables. ...


In its whole, exception handling code might look like this (in pseudocode): Pseudocodes can refer to the technique of using short codes, especially within the language with singular name Short Code, which was the first ever language developed for an electronic computing device. ...

 try { line = console.readLine(); if (line.length() == 0) { throw new EmptyLineException("The line read from console was empty!"); } console.printLine("Hello %s!" % line); } catch (EmptyLineException e) { console.printLine("Hello!"); } catch (Exception e) { console.printLine("Error: " + e.message()); } else { console.printLine("The program ran successfully"); } finally { console.printLine("The program terminates now"); } 

As a minor variation, some languages use a single handler clause, which deals with the class of the exception internally.


Languages such as Perl and C don't use the term exception handling, but include facilities that allow implementing them.


Checked exceptions

Designers of Java introduced to the language checked exceptions which are a special set of exceptions. The checked exceptions that may arise when calling a method constitute part of the type of the method. For instance, if a method might throw an IOException instead of returning successfully, it must declare this fact in its method header. Failure to do so raises a compile-time error.


This is related to exception checkers that exist at least for OCaml. The external tool for OCaml is both transparent (i.e. it does 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). Objective Caml (OCaml) is a general-purpose programming language descended from the ML family, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996. ...


The CLU programming language had a feature that was technically closer to what Java has introduced later. A function could raise only exceptions listed in its type, but any leaking exceptions from called functions would automatically be turned into the sole runtime exception, failure, instead of resulting in compile-time error. CLU is a programming language created at MIT by Barbara Liskov and her students between 1974 and 1975. ...


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; the unchecked exceptions (RuntimeExceptions and Errors) can still go unhandled.


However, some see checked exceptions as a nuisance, syntactic salt that either requires large throws declarations, often revealing implementation details and reducing encapsulation, or encourages the (ab)use of poorly-considered try/catch blocks that can potentially hide legitimate exceptions from their appropriate handlers. Syntactic sugar is a term coined by Peter J. Landin for additions to the syntax of a computer language that do not affect its expressiveness but make it sweeter for humans to use. ...


Others do not consider this a nuisance as you can reduce the number of declared exceptions by either declaring a superclass of all potentionally thrown exceptions or by defining and declaring exception types that are suitable for the level of abstraction of the called method (Bloch 2001:178), and mapping lower level exceptions to these types, preferably wrapped using the exception chaining in order to preserve the root cause. In computer science, a superclass is a class from which other classes are derived. ... Exception chaining AKA exception wrapping is an object-oriented programming technique of wrapping exceptions into exceptions by saving original exception, i. ...


A simple throws Exception declaration or catch (Exception e) is always sufficient to satisfy the checking. While this technique is sometimes useful, it effectively circumvents the checked exception mechanism, so it should only be used after careful consideration.


One prevalent view is that unchecked exception types should not be handled, except maybe at the outermost levels of scope, as they often represent scenarios that do not allow for recovery: RuntimeExceptions frequently reflect programming defects (Bloch 2001:172), and Errors generally represent unrecovereable JVM failures. The view is that, even in a language that supports checked exceptions, there are cases where the use of checked exceptions is not appropriate.


Condition systems

Common Lisp, 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. Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, standardised by ANSI X3. ... The Dylan programming language (pronounced , like the name) is functional, object-oriented, reflective and dynamic. ... Smalltalk is an object-oriented, dynamically typed, reflective programming language designed at Xerox PARC by Alan Kay, Dan Ingalls, Ted Kaehler, Adele Goldberg, and others during the 1970s, influenced by Sketchpad and Simula. ... Kent M. Pitman is the President of HyperMeta, Inc. ...


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. [1]


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. 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. In computing, booting is a bootstrapping process that starts operating systems when the user turns on a computer system. ...


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 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. syslog is a de facto standard for forwarding log messages in an IP network. ...


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 mechanisms available for recovering from error; the selection of restart by the condition handler supplies the policy. Mechanism is the following: In general, a mechanism is part of a chain of causes leading to some object or process. ... A policy is a plan of action for tackling issues. ...


References

  1. ^ Bloch, Joshua (2001). Effective Java Programming Language Guide. Addison-Wesley Professional. ISBN 0-201-31005-8.

See also

A triple fault is a special kind of exception generated by the CPU when an exception occurs while the CPU is trying to invoke the double fault exception handler, which itself handles exceptions occurring while trying to invoke a regular exception handler. ... This page is about the computer science continuation. ...

External links


  Results from FactBites:
 
Exception handling - Wikipedia, the free encyclopedia (1834 words)
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution.
Exception handling is intended to facilitate use of reasonable mechanisms for handling erroneous or exceptional situations that arise in programs.
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.
  More results at FactBites »

 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m