HOME

TheInfoList



OR:

In
computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes, and development of both hardware and software. Computing has scientific, e ...
and
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the
execution Capital punishment, also known as the death penalty, is the State (polity), state-sanctioned practice of deliberately killing a person as a punishment for an actual or supposed crime, usually following an authorized, rule-governed process to ...
of a
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Progra ...
. In general, an exception breaks the normal flow of execution and executes a pre-registered ''exception handler''; the details of how this is done depend on whether it is a hardware or
software Software is a set of computer programs and associated documentation and data. This is in contrast to hardware, from which the system is built and which actually performs the work. At the lowest programming level, executable code consists ...
exception and how the software exception is implemented. Exception handling, if provided, is facilitated by specialized
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
constructs, hardware mechanisms like
interrupt In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted, ...
s, or
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
(OS)
inter-process communication In computer science, inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow the processes to manage shared data. Typically, applications can use IPC, categori ...
(IPC) facilities like
signals In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The ''IEEE Transactions on Signal Processing'' ...
. Some exceptions, especially hardware ones, may be handled so gracefully that execution can resume where it was interrupted.


Definition

The definition of an exception is based on the observation that each procedure has a
precondition In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification. If a precondition is violated, the effect of the s ...
, a set of circumstances for which it will terminate "normally". An exception handling mechanism allows the procedure to ''raise an exception'' if this precondition is violated, for example if the procedure has been called on an abnormal set of arguments. The exception handling mechanism then ''handles'' the exception. The precondition, and the definition of exception, is subjective. The set of "normal" circumstances is defined entirely by the programmer, e.g. the programmer may deem division by zero to be undefined, hence an exception, or devise some behavior such as returning zero or a special "ZERO DIVIDE" value (circumventing the need for exceptions). Common exceptions include an invalid argument (e.g. value is outside of the
domain of a function In mathematics, the domain of a function is the set of inputs accepted by the function. It is sometimes denoted by \operatorname(f) or \operatornamef, where is the function. More precisely, given a function f\colon X\to Y, the domain of is . ...
), an unavailable resource (like a missing file, a hard disk error, or out-of-memory errors), or that the routine has detected a normal condition that requires special handling, e.g., attention, end of file. Exception handling solves the
semipredicate problem In computer programming, a semipredicate problem occurs when a subroutine intended to return a useful value can fail, but the signalling of failure uses an otherwise valid return value. The problem is that the caller of the subroutine cannot tell ...
, in that the mechanism distinguishes normal return values from erroneous ones. In languages without built-in exception handling such as C, routines would need to signal the error in some other way, such as the common
return code In computer programming, a return code or an error code is a numeric or alphanumeric code that is used to determine the nature of an error and why it occurred. They are also commonly found in consumer electronics and devices when they attempt to ...
and
errno errno.h is a header file in the standard library of the C programming language. It defines macros for reporting and retrieving error conditions using the symbol errno (short for "error number").International Standard for Programming Language C ...
pattern. Taking a broad view, errors can be considered to be a proper subset of exceptions, and explicit error mechanisms such as errno can be considered (verbose) forms of exception handling. The term "exception" is preferred to "error" because it does not imply that anything is wrong - a condition viewed as an error by one procedure or programmer may not be viewed that way by another. Even the term "exception" may be misleading because its typical connotation of "outlier" indicates that something infrequent or unusual has occurred, when in fact raising the exception may be a normal and usual situation in the program. For example, suppose a lookup function for an
associative array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an as ...
throws an exception if the key has no value associated. Depending on context, this "key absent" exception may occur much more often than a successful lookup. A major influence on the scope and use of exceptions is social pressure, i.e. "examples of use, typically found in core libraries, and code examples in technical books, magazine articles, and online discussion forums, and in an organization’s code standards".


History

The first hardware exception handling was found in the
UNIVAC I The UNIVAC I (Universal Automatic Computer I) was the first general-purpose electronic digital computer design for business application produced in the United States. It was designed principally by J. Presper Eckert and John Mauchly, the invento ...
from 1951. Arithmetic overflow executed two instructions at address 0, which could transfer control or fix up the result. Software exception handling developed in the 1960s and 1970s. LISP 1.5 (1958-1961) allowed exceptions to be raised by the ERROR pseudo-function, similarly to errors raised by the interpreter or compiler. Exceptions were caught by the ERRORSET keyword, which returned NIL in case of an error, instead of terminating the program or entering the debugger.
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
introduced its own form of exception handling circa 1964, allowing interrupts to be handled with ON units. MacLisp observed that ERRSET and ERR were used not only for error raising, but for non-local control flow, and thus added two new keywords, CATCH and THROW (June 1972). The cleanup behavior now generally called "finally" was introduced in
NIL Nil may refer to: * nil (the number 0, zero) Acronyms * NIL (programming language), an implementation of the Lisp programming language * Student athlete compensation, Name, Image and Likeness, a set of rules in the American National Collegiate At ...
(New Implementation of LISP) in the mid- to late-1970s as UNWIND-PROTECT. This was then adopted by
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
. Contemporary with this was dynamic-wind in Scheme, which handled exceptions in closures. The first papers on structured exception handling were and . Exception handling was subsequently widely adopted by many programming languages from the 1980s onward.


Hardware exceptions

There is no clear consensus as to the exact meaning of an exception with respect to hardware. From the implementation point of view, it is handled identically to an
interrupt In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted, ...
: the processor halts execution of the current program, looks up the
interrupt handler In computer systems programming, an interrupt handler, also known as an interrupt service routine or ISR, is a special block of code associated with a specific interrupt condition. Interrupt handlers are initiated by hardware interrupts, softwar ...
in the
interrupt vector table An interrupt vector table (IVT) is a data structure that associates a list of interrupt handlers with a list of interrupt requests in a table of interrupt vectors. Each entry of the interrupt vector table, called an interrupt vector, is the addr ...
for that exception or interrupt condition, saves state, and switches control.


IEEE 754 floating-point exceptions

Exception handling in the
IEEE 754 The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found i ...
floating-point In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can b ...
standard refers in general to exceptional conditions and defines an exception as "an event that occurs when an operation on some particular operands has no outcome suitable for every reasonable application. That operation might signal one or more exceptions by invoking the default or, if explicitly requested, a language-defined alternate handling." By default, an IEEE 754 exception is resumable and is handled by substituting a predefined value for different exceptions, e.g. infinity for a divide by zero exception, and providing status flags for later checking of whether the exception occurred (see C99 programming language for a typical example of handling of IEEE 754 exceptions). An exception-handling style enabled by the use of status flags involves: first computing an expression using a fast, direct implementation; checking whether it failed by testing status flags; and then, if necessary, calling a slower, more numerically robust, implementation. The IEEE 754 standard uses the term "trapping" to refer to the calling of a user-supplied exception-handling routine on exceptional conditions, and is an optional feature of the standard. The standard recommends several usage scenarios for this, including the implementation of non-default pre-substitution of a value followed by resumption, to concisely handle removable singularities. The default IEEE 754 exception handling behaviour of resumption following pre-substitution of a default value avoids the risks inherent in changing flow of program control on numerical exceptions. For example, the 1996 Cluster spacecraft launch ended in a catastrophic explosion due in part to the
Ada Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, ...
exception handling policy of aborting computation on arithmetic error.
William Kahan William "Velvel" Morton Kahan (born June 5, 1933) is a Canadian mathematician and computer scientist, who received the Turing Award in 1989 for "''his fundamental contributions to numerical analysis''", was named an ACM Fellow in 1994, and inducte ...
claims the default IEEE 754 exception handling behavior would have prevented this.


Exception support in programming languages

Software exception handling and the support provided by software tools differs somewhat from what is understood by exception handling in hardware, but similar concepts are involved. In programming language mechanisms for exception handling, the term ''exception'' is typically used in a specific sense to denote a data structure storing information about an exceptional condition. One mechanism to transfer control, or ''raise'' an exception, is known as a ''throw''. The exception is said to be ''thrown''. Execution is transferred to a "catch". Programming languages differ substantially in their notion of what an exception is. Contemporary languages can roughly be divided into two groups: * Languages where exceptions are designed to be used as flow control structures: Ada, Modula-3, ML, OCaml, PL/I, Python, and Ruby fall in this category. For example, Python's iterators throw StopIteration exceptions to signal that there are no further items produced by the iterator. * Languages where exceptions are only used to handle abnormal, unpredictable, erroneous situations: C++, Java, C#, Common Lisp, Eiffel, and Modula-2. PL/I used dynamically scoped exceptions. PL/I exception handling included events that are not errors, e.g., attention, end-of-file, modification of listed variables.


Syntax

Many computer languages have built-in syntactic support for exceptions and exception handling. This includes
ActionScript ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning i ...
,
Ada Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, ...
, BlitzMax,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, C#,
Clojure Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
,
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
, D,
ECMAScript ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
,
Eiffel Eiffel may refer to: Places * Eiffel Peak, a summit in Alberta, Canada * Champ de Mars – Tour Eiffel station, Paris, France; a transit station Structures * Eiffel Tower, in Paris, France, designed by Gustave Eiffel * Eiffel Bridge, Ungheni, M ...
,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, ML,
Object Pascal Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods. ...
(e.g.
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracle ...
,
Free Pascal Free Pascal Compiler (FPC) is a compiler for the closely related programming-language dialects Pascal and Object Pascal. It is free software released under the GNU General Public License, witexception clausesthat allow static linking against it ...
, and the like),
PowerBuilder PowerBuilder is an integrated development environment owned by SAP since the acquisition of Sybase in 2010. On July 5, 2016, SAP and Appeon entered into an agreement whereby Appeon, an independent company, would be responsible for developing, se ...
,
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
,
OCaml OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
,
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
(as of version 5),
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
,
PL/SQL PL/SQL (Procedural Language for SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 6 - stored PL/SQL procedures/functions/packages/triggers since ...
,
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
REALbasic The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a propri ...
,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, Scala,
Seed7 Seed7 is an extensible general-purpose programming language designed by Thomas Mertes. It is syntactically similar to Pascal and Ada. Along with many other features, it provides an extension mechanism. Daniel Zingaro"Modern Extensible Languages" ...
,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
,
Tcl TCL or Tcl or TCLs may refer to: Business * TCL Technology, a Chinese consumer electronics and appliance company **TCL Electronics, a subsidiary of TCL Technology * Texas Collegiate League, a collegiate baseball league * Trade Centre Limited ...
,
Visual Prolog Visual Prolog, previously known as PDC Prolog and Turbo Prolog, is a strongly typed object-oriented extension of Prolog. As Turbo Prolog, it was marketed by Borland but it is now developed and marketed by the Danish firm PDC that originally creat ...
and most .NET languages. 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 (e.g. with Java or Object Pascal) or a value of a special extendable enumerated type (e.g. with Ada or SML). 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 types it handles and what name it uses for the exception object. As a minor variation, some languages use a single handler clause, which deals with the class of the exception internally. Also common is a related clause (finally or ensure) that is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block. Notably, C++ does not provide this construct, recommending instead the Resource Acquisition Is Initialization (RAII) technique which frees resources using destructors. According to a 2008 paper by Westley Weimer and
George Necula George Ciprian Necula is a Romanian computer scientist, engineer at Google, and former professor at the University of California, Berkeley who does research in the area of programming languages and software engineering, with a particular focus on ...
, the syntax of the try...finally blocks in Java is a contributing factor to software defects. When a method needs to handle the acquisition and release of 3–5 resources, programmers are apparently unwilling to nest enough blocks due to readability concerns, even when this would be a correct solution. It is possible to use a single try...finally block even when dealing with multiple resources, but that requires a correct use of
sentinel value In computer programming, a sentinel value (also referred to as a flag value, trip value, rogue value, signal value, or dummy data) is a special value in the context of an algorithm which uses its presence as a condition of termination, typically in ...
s, which is another common source of bugs for this type of problem. Python and Ruby also permit a clause (else) that is used in case no exception occurred before the end of the handler's scope was reached. In its whole, exception handling code might look like this (in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
-like
pseudocode In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
): try catch (EmptyLineException e) catch (Exception e) else finally C does not have try-catch exception handling, but uses
return code In computer programming, a return code or an error code is a numeric or alphanumeric code that is used to determine the nature of an error and why it occurred. They are also commonly found in consumer electronics and devices when they attempt to ...
s for error checking. The setjmp and longjmp standard library functions can be used to implement try-catch handling via macros.
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
5 uses die for throw and eval if ($@) for try-catch. It has CPAN modules that offer try-catch semantics.


Termination and resumption semantics

When an exception is thrown, the program searches back through the
stack Stack may refer to: Places * Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group * Blue Stack Mountains, in Co. Donegal, Ireland People * Stack (surname) (including a list of people ...
of function calls until an exception handler is found. Some languages call for unwinding the stack as this search progresses. That is, if function , containing a handler for exception , calls function , which in turn calls function , and an exception occurs in , then functions and may be terminated, and in will handle . This is said to be termination semantics. Alternately, the exception handling mechanisms may not unwind the stack on entryIn, e.g., PL/I, a normal exit from an exception handler unwinds the stack. to an exception handler, giving the exception handler the option to restart the computation, resume or unwind. This allows the program to continue the computation at exactly the same place where the error occurred (for example when a previously missing file has become available) or to implement notifications, logging, queries and fluid variables on top of the exception handling mechanism (as done in Smalltalk). Allowing the computation to resume where it left off is termed resumption semantics. There are theoretical and design arguments in favor of either decision. C++ standardization discussions in 1989–1991 resulted in a definitive decision to use termination semantics in C++.
Bjarne Stroustrup Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University. ...
cites a presentation by Jim Mitchell as a key data point: Exception-handling languages with resumption include
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
with its
Condition System Condition or conditions may refer to: In philosophy and logic * Material conditional, a logical connective used to form "if...then..." statements * Necessary and sufficient condition, a statement which is true if and only if another given state ...
, PL/I, Dylan, R, and
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
. However, the majority of newer programming languages follow C++ and use termination semantics.


Exception handling implementation

The implementation of exception handling in programming languages typically involves a fair amount of support from both a code generator and the
runtime system In computer programming, a runtime system or runtime environment is a sub-system that exists both in the computer where a program is created, as well as in the computers where the program is intended to be run. The name comes from the compile t ...
accompanying a compiler. (It was the addition of exception handling to C++ that ended the useful lifetime of the original C++ compiler,
Cfront Cfront was the original compiler for C++ (then known as " C with Classes") from around 1983, which converted C++ to C; developed by Bjarne Stroustrup at AT&T Bell Labs. The preprocessor did not understand all of the language and much of the code wa ...
.) Two schemes are most common. The first, ', generates code that continually updates structures about the program state in terms of exception handling. Typically, this adds a new element to the stack frame layout that knows what handlers are available for the function or method associated with that frame; if an exception is thrown, a pointer in the layout directs the runtime to the appropriate handler code. This approach is compact in terms of space, but adds execution overhead on frame entry and exit. It was commonly used in many Ada implementations, for example, where complex generation and runtime support was already needed for many other language features. Microsoft's 32-bit
Structured Exception Handling The Microsoft Windows family of operating systems employ some specific exception handling mechanisms. Structured Exception Handling Microsoft Structured Exception Handling is the native exception handling mechanism for Windows and a forerunner te ...
(SEH) uses this approach with a separate exception stack. Dynamic registration, being fairly straightforward to define, is amenable to
proof of correctness In theoretical computer science, an algorithm is correct with respect to a specification if it behaves as specified. Best explored is ''functional'' correctness, which refers to the input-output behavior of the algorithm (i.e., for each input it p ...
. The second scheme, and the one implemented in many production-quality C++ compilers and 64-bit Microsoft SEH, is a . This creates static tables at
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
and
link time In computer science, link time refers to the period of time, during the creation of a computer program, in which a linker is being applied to that program. Link time occurs after compile time and before runtime (when a program is executed). It i ...
that relate ranges of the
program counter The program counter (PC), commonly called the instruction pointer (IP) in Intel x86 and Itanium microprocessors, and sometimes called the instruction address register (IAR), the instruction counter, or just part of the instruction sequencer, is ...
to the program state with respect to exception handling. Then, if an exception is thrown, the runtime system looks up the current instruction location in the tables and determines what handlers are in play and what needs to be done. This approach minimizes executive overhead for the case where an exception is not thrown. This happens at the cost of some space, but this space can be allocated into read-only, special-purpose data sections that are not loaded or relocated until an exception is actually thrown. The location (in memory) of the code for handling an exception need not be located within (or even near) the region of memory where the rest of the function's code is stored. So if an exception is thrown then a performance hit – roughly comparable to a function call – may occur if the necessary exception handling code needs to be loaded/cached. However, this scheme has minimal performance cost if no exception is thrown. Since exceptions in C++ are supposed to be ''exceptional'' (i.e. uncommon/rare) events, the phrase "zero-cost exceptions"There is "zero rocessingcost" only if no exception is throw (although there will be a memory cost since memory is needed for the lookup table). There is a (potentially significant) cost if an exception is thrown (that is, if throw is executed). Implementing exception handling may also limit the possible
compiler optimizations In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power con ...
that may be performed.
is sometimes used to describe exception handling in C++. Like
runtime type identification In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time typ ...
(RTTI), exceptions might not adhere to C++'
zero-overhead principle
as implementing exception handling at run-time requires a non-zero amount of memory for the lookup table. For this reason, exception handling (and RTTI) can be disabled in many C++ compilers, which may be useful for systems with very limited memory (such as
embedded system An embedded system is a computer system—a combination of a computer processor, computer memory, and input/output peripheral devices—that has a dedicated function within a larger mechanical or electronic system. It is ''embedded'' as ...
s). This second approach is also superior in terms of achieving
thread safety Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without uni ...
. Other definitional and implementation schemes have been proposed as well. For languages that support
metaprogramming Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself ...
, approaches that involve no overhead at all (beyond the already present support for
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in ...
) have been advanced.


Exception handling based on design by contract

A different view of exceptions is based on the principles of design by contract and is supported in particular by the Eiffel language. The idea is to provide a more rigorous basis for exception handling by defining precisely what is "normal" and "abnormal" behavior. Specifically, the approach is based on two concepts: * Failure: the inability of an operation to fulfill its contract. For example, an addition may produce an arithmetic overflow (it does not fulfill its contract of computing a good approximation to the mathematical sum); or a routine may fail to meet its postcondition. * Exception: an abnormal event occurring during the execution of a routine (that routine is the "''recipient''" of the exception) during its execution. Such an abnormal event results from the ''failure'' of an operation called by the routine. The "Safe Exception Handling principle" as introduced by Bertrand Meyer in
Object-Oriented Software Construction ''Object-Oriented Software Construction'' is a book by Bertrand Meyer, widely considered a foundational text of object-oriented programming. The first edition was published in 1988; the second, extensively revised and expanded edition (more than 1 ...
then holds that there are only two meaningful ways a routine can react when an exception occurs: * Failure, or "organized panic": The routine fixes the object's state by re-establishing the invariant (this is the "organized" part), and then fails (panics), triggering an exception in its caller (so that the abnormal event is not ignored). * Retry: The routine tries the algorithm again, usually after changing some values so that the next attempt will have a better chance to succeed. In particular, simply ignoring an exception is not permitted; a block must either be retried and successfully complete, or propagate the exception to its caller. Here is an example expressed in Eiffel syntax. It assumes that a routine is normally the better way to send a message, but it may fail, triggering an exception; if so, the algorithm next uses , which will fail less often. If fails, the routine as a whole should fail, causing the caller to get an exception. send (m: MESSAGE) is -- Send m through fast link, if possible, otherwise through slow link. local tried_fast, tried_slow: BOOLEAN do if tried_fast then tried_slow := True send_slow (m) else tried_fast := True send_fast (m) end rescue if not tried_slow then retry end end The boolean local variables are initialized to False at the start. If fails, the body ( clause) will be executed again, causing execution of . If this execution of fails, the clause will execute to the end with no (no clause in the final ), causing the routine execution as a whole to fail. This approach has the merit of defining clearly what "normal" and "abnormal" cases are: an abnormal case, causing an exception, is one in which the routine is unable to fulfill its contract. It defines a clear distribution of roles: the clause (normal body) is in charge of achieving, or attempting to achieve, the routine's contract; the clause is in charge of reestablishing the context and restarting the process, if this has a chance of succeeding, but not of performing any actual computation. Although exceptions in Eiffel have a fairly clear philosophy, Kiniry (2006) criticizes their implementation because "Exceptions that are part of the language definition are represented by INTEGER values, developer-defined exceptions by STRING values. ..Additionally, because they are basic values and not objects, they have no inherent semantics beyond that which is expressed in a helper routine which necessarily cannot be foolproof because of the representation overloading in effect (e.g., one cannot differentiate two integers of the same value)."


Uncaught exceptions

Contemporary applications face many design challenges when considering exception handling strategies. Particularly in modern enterprise level applications, exceptions must often cross process boundaries and machine boundaries. Part of designing a solid exception handling strategy is recognizing when a process has failed to the point where it cannot be economically handled by the software portion of the process. If an exception is thrown and not caught (operationally, an exception is thrown when there is no applicable handler specified), the uncaught exception is handled by the runtime; the routine that does this is called the .''Mac Developer Library'',
Uncaught Exceptions
"
The most common default behavior is to terminate the program and print an error message to the console, usually including debug information such as a string representation of the exception and the
stack trace In computing, a stack trace (also called stack backtrace or stack traceback) is a report of the active stack frames at a certain point in time during the execution of a program. When a program is run, memory is often dynamically allocated in two p ...
. This is often avoided by having a top-level (application-level) handler (for example in an
event loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
) that catches exceptions before they reach the runtime.PyMOTW (Python Module Of The Week),
Exception Handling
"
Note that even though an uncaught exception may result in the ''program'' terminating abnormally (the program may not be correct if an exception is not caught, notably by not rolling back partially completed transactions, or not releasing resources), the ''process'' terminates normally (assuming the runtime works correctly), as the runtime (which is controlling execution of the program) can ensure orderly shutdown of the process. In a multithreaded program, an uncaught exception in a thread may instead result in termination of just that thread, not the entire process (uncaught exceptions in the thread-level handler are caught by the top-level handler). This is particularly important for servers, where for example a
servlet A Jakarta Servlet (formerly Java Servlet) is a Java software component that extends the capabilities of a server. Although servlets can respond to many types of requests, they most commonly implement web containers for hosting web application ...
(running in its own thread) can be terminated without the server overall being affected. This default uncaught exception handler may be overridden, either globally or per-thread, for example to provide alternative logging or end-user reporting of uncaught exceptions, or to restart threads that terminate due to an uncaught exception. For example, in Java this is done for a single thread via Thread.setUncaughtExceptionHandler
/code> and globally via
/code>; in Python this is done by modifying
/code>.


Checked exceptions

Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
introduced the notion of checked exceptions, which are special classes of exceptions. The checked exceptions that a method may raise must be part of the method's
signature A signature (; from la, signare, "to sign") is a handwritten (and often stylized) depiction of someone's name, nickname, or even a simple "X" or other mark that a person writes on documents as a proof of identity and intent. The writer of a ...
. For instance, if a method might throw an , it must declare this fact explicitly in its method signature. Failure to do so raises a compile-time error. According to Hanspeter Mössenböck, checked exceptions are less convenient but more robust. Checked exceptions can, at
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
, reduce the incidence of unhandled exceptions surfacing at runtime in a given application. Kiniry writes that "As any Java programmer knows, the volume of
try catch In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the Execution (computing), execution of a C ...
code in a typical Java application is sometimes larger than the comparable code necessary for explicit formal parameter and return value checking in other languages that do not have checked exceptions. In fact, the general consensus among in-the-trenches Java programmers is that dealing with checked exceptions is nearly as unpleasant a task as writing documentation. Thus, many programmers report that they “resent” checked exceptions.". Martin Fowler has written "...on the whole I think that exceptions are good, but Java checked exceptions are more trouble than they are worth." As of 2006 no major programming language has followed Java in adding checked exceptions. For example, C# does not require or allow declaration of any exception specifications, with the following posted by Eric Gunnerson:
Anders Hejlsberg Anders Hejlsberg (, born 2 December 1960) is a Danish software engineer who co-designed several programming languages and development tools. He was the original author of Turbo Pascal and the chief architect of Delphi. He currently works for Mic ...
describes two concerns with checked exceptions: * Versioning: A method may be declared to throw exceptions X and Y. In a later version of the code, one cannot throw exception Z from the method, because it would make the new code incompatible with the earlier uses. Checked exceptions require the method's callers to either add Z to their throws clause or handle the exception. Alternately, Z may be misrepresented as an X or a Y. * Scalability: In a hierarchical design, each systems may have several subsystems. Each subsystem may throw several exceptions. Each parent system must deal with the exceptions of all subsystems below it, resulting in an exponential number of exceptions to be dealt with. Checked exceptions require all of these exceptions to be dealt with explicitly. To work around these, Hejlsberg says programmers resort to circumventing the feature by using a declaration. Another circumvention is to use a handler. This is referred to as catch-all exception handling or Pokémon exception handling after
the show Show or The Show may refer to: Competition, event, or artistic production * Agricultural show, associated with agriculture and animal husbandry * Animal show, a judged event in the hobby of animal fancy ** Cat show ** Dog show ** Horse show ** Sp ...
's catchphrase "Gotta Catch ‘Em All!". The Java Tutorials discourage catch-all exception handling as it may catch exceptions "for which the handler was not intended". Still another discouraged circumvention is to make all exceptions subclass . An encouraged solution is to use a catch-all handler or throws clause but with a specific superclass of all potentially thrown exceptions rather than the general superclass . Another encouraged solution is to define and declare exception types that are suitable for the level of abstraction of the called method and map lower level exceptions to these types by using
exception chaining Exception chaining, or exception wrapping, is an object-oriented programming technique of exception handling, handling exceptions by re-throwing a caught exception after wrapping it inside a new exception. The original exception is saved as a proper ...
.


Similar mechanisms

The roots of checked exceptions go back to the
CLU programming language CLU is a programming language created at the Massachusetts Institute of Technology (MIT) by Barbara Liskov and her students starting in 1973.Liskov, Barbara (1992). "A history of CLU". The second ACM SIGPLAN conference on History of programming ...
's notion of exception specification. 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, , instead of resulting in compile-time error. Later,
Modula-3 Modula-3 is a programming language conceived as a successor to an upgraded version of Modula-2 known as Modula-2+. While it has been influential in research circles (influencing the designs of languages such as Java, C#, and Python) it has not be ...
had a similar feature. These features don't include the compile time checking that is central in the concept of checked exceptions. Early versions of the C++ programming language included an optional mechanism similar to checked exceptions, called exception specifications. By default any function could throw any exception, but this could be limited by a clause added to the function signature, that specified which exceptions the function may throw. Exception specifications were not enforced at compile-time. Violations resulted in the global function being called.
Bjarne Stroustrup Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University. ...
, ''
The C++ Programming Language ''The C++ Programming Language'' is a computer programming book first published in October 1985. It was the first book to describe the C++ programming language, written by the language's creator, Bjarne Stroustrup. In the absence of an official s ...
'' Third Edition,
Addison Wesley Addison-Wesley is an American publisher of textbooks and computer literature. It is an imprint of Pearson PLC, a global publishing and education company. In addition to publishing books, Addison-Wesley also distributes its technical titles through ...
, 1997. . pp. 375-380.
An empty exception specification could be given, which indicated that the function will throw no exception. This was not made the default when exception handling was added to the language because it would have required too much modification of existing code, would have impeded interaction with code written in other languages, and would have tempted programmers into writing too many handlers at the local level. Explicit use of empty exception specifications could, however, allow C++ compilers to perform significant code and stack layout optimizations that are precluded when exception handling may take place in a function. Some analysts viewed the proper use of exception specifications in C++ as difficult to achieve. This use of exception specifications was included in
C++98 C98 or C-98 may refer to: * C-98 Clipper, the military designation of the Boeing 314 flying boat * CJYC-FM, "Big John FM", formerly known as "C98" * Cray C98, a model of the Cray C90 * Ruy Lopez (ECO code), a chess opening * Lake Village Airport (F ...
and
C++03 C, or c, is the third letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''cee'' (pronounced ), plural ''cees''. History "C" ...
,
deprecated In several fields, especially computing, deprecation is the discouragement of use of some terminology, feature, design, or practice, typically because it has been superseded or is no longer considered efficient or safe, without completely removing ...
in the 2012 C++ language standard (
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
), and was removed from the language in
C++17 C++17 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++17 replaced the prior version of the C++ standard, called C++14, and was later replaced by C++20. History Before the C++ Standards Committee fixed a 3-year rel ...
. A function that will not throw any exceptions can now be denoted by the keyword. An uncaught exceptions analyzer exists for the
OCaml OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
programming language. The tool reports the set of raised exceptions as an extended type signature. But, unlike checked exceptions, the tool does not require any syntactic annotations and is external (i.e. it is possible to compile and run a program without having checked the exceptions).


Dynamic checking of exceptions

The point of exception handling routines is to ensure that the code can handle error conditions. In order to establish that exception handling routines are sufficiently robust, it is necessary to present the code with a wide spectrum of invalid or unexpected inputs, such as can be created via software
fault injection In computer science, fault injection is a testing technique for understanding how computing systems behave when stressed in unusual ways. This can be achieved using physical- or software-based means, or using a hybrid approach. Widely studied phys ...
and
mutation testing Mutation testing (or ''mutation analysis'' or ''program mutation'') is used to design new software tests and evaluate the quality of existing software tests. Mutation testing involves modifying a program in small ways. Each mutated version is call ...
(that is also sometimes referred to as
fuzz testing Fuzz may refer to: * Fuzz (film), ''Fuzz'' (film), a 1972 American comedy * ''Fuzz: When Nature Breaks the Law'', a nonfiction book by Mary Roach * The fuzz, a List of slang terms for police officers, slang term for police officers Music * Fuzz ...
). One of the most difficult types of software for which to write exception handling routines is protocol software, since a robust protocol implementation must be prepared to receive input that does not comply with the relevant specification(s). In order to ensure that meaningful regression analysis can be conducted throughout a software development lifecycle process, any exception handling testing should be highly automated, and the test cases must be generated in a scientific, repeatable fashion. Several commercially available systems exist that perform such testing. In runtime engine environments such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
or .NET, there exist tools that attach to the runtime engine and every time that an exception of interest occurs, they record debugging information that existed in memory at the time the exception was thrown (
call stack In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or ma ...
and heap values). These tools are called
automated exception handling Automated exception handling is a computing term referring to the computerized handling of errors. Runtime systems (engines) such as those for the Java programming language or .NET Framework lend themselves to an automated mode of exception or er ...
or error interception tools and provide 'root-cause' information for exceptions.


Asynchronous exceptions

Asynchronous exceptions are events raised by a separate thread or external process, such as pressing Ctrl-C to interrupt a program, receiving a
signal In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The ''IEEE Transactions on Signal Processing'' ...
, or sending a disruptive message such as "stop" or "suspend" from another thread of execution. Whereas synchronous exceptions happen at a specific throw statement, asynchronous exceptions can be raised at any time. It follows that asynchronous exception handling can't be optimized out by the compiler, as it cannot prove the absence of asynchronous exceptions. They are also difficult to program with correctly, as asynchronous exceptions must be blocked during cleanup operations to avoid resource leaks. Programming languages typically avoid or restrict asynchronous exception handling, for example C++ forbids raising exceptions from signal handlers, and Java has deprecated the use of its ThreadDeath exception that was used to allow one thread to stop another one. Another feature is a semi-asynchronous mechanism that raises an asynchronous exception only during certain operations of the program. For example Java's only affects the thread when the thread calls an operation that throws . The similar POSIX API has race conditions which make it impossible to use safely.


Condition systems

Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
, Dylan and
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
have a
condition system Condition or conditions may refer to: In philosophy and logic * Material conditional, a logical connective used to form "if...then..." statements * Necessary and sufficient condition, a statement which is true if and only if another given state ...
(see Common Lisp Condition System) that 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 Kent M. Pitman (KMP) is a programmer who has been involved for many years in the design, implementation, and use of systems based on the programming languages Lisp and Scheme. , he has been President of HyperMeta, Inc. Pitman was chair of the ad h ...
) 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 that do not represent errors may safely go unhandled entirely; their only purpose may be to propagate hints or warnings toward the user.


Continuable exceptions

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. An example is the ENDPAGE condition in PL/I; the ON unit might write page trailer lines and header lines for the next page, then fall through to resume execution of the interrupted code.


Restarts separate mechanism from policy

Condition handling moreover provides a
separation of mechanism from policy The separation of mechanism and policy is a design principle in computer science. It states that mechanisms (those parts of a system implementation that control the authorization of operations and the allocation of resources) should not dictate (or ...
. 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 access to a broader view. An example: Suppose there is a library function whose purpose is to parse a single
syslog In computing, syslog is a standard for message logging. It allows separation of the software that generates messages, the system that stores them, and the software that reports and analyzes them. Each message is labeled with a facility code, i ...
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 ''mechanisms'' available for recovering from error; the selection of restart by the condition handler supplies the ''
policy Policy is a deliberate system of guidelines to guide decisions and achieve rational outcomes. A policy is a statement of intent and is implemented as a procedure or protocol. Policies are generally adopted by a governance body within an organ ...
''.


Criticism

Exception handling is often not handled correctly in software, especially when there are multiple sources of exceptions;
data flow analysis In the pursuit of knowledge, data (; ) is a collection of discrete values that convey information, describing quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted. ...
of 5 million lines of Java code found over 1300 exception handling defects. Citing multiple prior studies by others (1999–2004) and their own results, Weimer and Necula wrote that a significant problem with exceptions is that they "create hidden control-flow paths that are difficult for programmers to reason about". "While try-catch-finally is conceptually simple, it has the most complicated execution description in the language specification
osling et al. 1996 The Oesling or Ösling () is a region covering the northern part of both the Grand Duchy of Luxembourg and Eifelkreis Bitburg-Prüm, within the greater Ardennes area that also covers parts of Belgium and France. The Oesling covers 32% of the terri ...
and requires four levels of nested “if”s in its official English description. In short, it contains a large number of
corner cases In engineering, a corner case (or pathological case) involves a problem or situation that occurs only outside normal operating parameters—specifically one that manifests itself when multiple environmental variables or conditions are simultaneou ...
that programmers often overlook." Exceptions, as unstructured flow, increase the risk of
resource leak In computer science, a resource leak is a particular type of resource consumption by a computer program where the program does not release resources it has acquired. This condition is normally the result of a bug in a program. Typical resource lea ...
s (such as escaping a section locked by a
mutex In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive: a mechanism that enforces limits on access to a resource when there are many threads of execution. A lock is designed to enforce a mutual exclusion concur ...
, or one temporarily holding a file open) or inconsistent state. There are various techniques for
resource management In organizational studies, resource management is the efficient and effective development of an organization's resources when they are needed. Such resources may include the financial resources, inventory, human skills, production resources, or i ...
in the presence of exceptions, most commonly combining the
dispose pattern In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method – usually called close, dispose, free, release dep ...
with some form of unwind protection (like a finally clause), which automatically releases the resource when control exits a section of code.
Tony Hoare Sir Charles Antony Richard Hoare (Tony Hoare or C. A. R. Hoare) (born 11 January 1934) is a British computer scientist who has made foundational contributions to programming languages, algorithms, operating systems, formal verification, and c ...
in 1980 described the
Ada programming language Ada is a structured, statically typed, imperative, and object-oriented high-level programming language, extended from Pascal and other languages. It has built-in language support for '' design by contract'' (DbC), extremely strong typing, explic ...
as having "...a plethora of features and notational conventions, many of them unnecessary and some of them, like exception handling, even dangerous. ..Do not allow this language in its present state to be used in applications where reliability is critical .. The next rocket to go astray as a result of a programming language error may not be an exploratory space rocket on a harmless trip to Venus: It may be a nuclear warhead exploding over one of our own cities." The Go developers believe that the try-catch-finally idiom obfuscates
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
, and introduced the exception-like / mechanism. differs from in that it can only be called from within a code block in a function, so the handler can only do clean-up and change the function's return values, and cannot return control to an arbitrary point within the function. The block itself functions similarly to a clause.


Exception handling in UI hierarchies

Front-end web frameworks, such as
React REACT or React may refer to: Science and technology *REACT (telescope), a telescope at Fenton Hill Observatory, New Mexico, US Computing * React (JavaScript library) , a JavaScript library for building user interfaces, from Facebook ** React Nati ...
and
Vue Vue or VUE may refer to: Places * Vue, Loire-Atlantique, a commune in France * The Vue, a skyscraper in Charlotte, North Carolina Arts, entertainment and media * Vue (band), a rock and roll band from San Francisco, California * Vue Cinemas, a c ...
, have introduced error handling mechanisms where errors propagate up the UI component hierarchy, in a way that is analogous to how errors propagate up the call stack in executing code. Here the error boundary mechanism serves as an analogue to the typical try-catch mechanism. Thus a component can ensure that errors from its child components are caught and handled, and not propagated up to parent components. For example, in Vue, a component would catch errors by implementing errorCaptured Vue.component('parent', ) Vue.component('child', ) When used like this in markup: The error produced by the child component is caught and handled by the parent component.


See also

*
Automated exception handling Automated exception handling is a computing term referring to the computerized handling of errors. Runtime systems (engines) such as those for the Java programming language or .NET Framework lend themselves to an automated mode of exception or er ...
*
Exception safety Exception safety is the state of code working correctly when exceptions are thrown. To aid in ensuring exception safety, C++ standard library developers have devised a set of ''exception safety levels'', contractual guarantees of the behavior of a ...
*
Continuation In computer science, a continuation is an abstract representation of the control state of a computer program. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computati ...
*
Defensive programming Defensive programming is a form of defensive design intended to develop programs that are capable of detecting potential security abnormalities and make predetermined responses. It ensures the continuing function of a piece of software under unf ...
*
Triple fault On the x86 computer architecture, 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 ...
*
Option type In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions whic ...
s and
Result type In functional programming, a result type is a Monadic type holding a returned value or an error code. They provide an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the ...
s, alternative ways of handling errors in
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
without exceptions *
Data validation In computer science, data validation is the process of ensuring data has undergone data cleansing to ensure they have data quality, that is, that they are both correct and useful. It uses routines, often called "validation rules", "validation cons ...


Notes


References

* * * * * * *


External links


A Crash Course on the Depths of Win32 Structured Exception Handling
by
Matt Pietrek Matt Pietrek (born January 27, 1966) is an American spirits and cocktail writer. Previously, he was a computer specialist and author specializing in Microsoft Windows. Pietrek also has a keen interest in cocktails and spirits, and he writes a blog ...
- Microsoft Systems Journal (1997) * Article
C++ Exception Handling
by Christophe de Dinechin * Article

by Brian Goetz * Article

by Arun Udaya Shankar * Article

by Kyle Loudon * Article

* Conference slide
Floating-Point Exception-Handling policies (pdf p. 46)
by William Kahan
Descriptions from Portland Pattern Repository

Does Java Need Checked Exceptions?
{{DEFAULTSORT:Exception Handling Control flow Software anomalies