Exception handling

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 of a program. 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 exception and how the software exception is implemented. It is provided by specialized programming language constructs, hardware mechanisms like interrupts, or operating system (OS) inter-process communication (IPC) facilities like signals. Some exceptions, especially hardware ones, may be handled so gracefully that execution can resume where it was interrupted.

  • anomalous [Origin: anomalus, from Greek, 'uneven, anomalous', from an- 'not' + homalos 'even']
  • abnormal [Origin: ab- 'away from, not' (from Latin ab- 'away, off') + normal]

An alternative approach to exception handling in software is error checking, which maintains normal program flow with later explicit checks for contingencies [可能发生也可能不发生的事件] reported using special return values, an auxiliary global variable such as C's errno, or floating point status flags. Input validation, which preemptively filters exceptional cases, is also an approach.

  • contingent [Origin: Latin, 现在分词 of contingere 'to have contact with, happen to', from com- + tangere 'to touch']
  • tangent [Origin: , 现在分词 of tangere; TANGIBLE] 圆的切线touch着圆
  • tangible [Origin: tangibilis, from Latin tangere 'to touch'] 可触知的; 明确的; 确切的; 真实的

perror(3) - Linux manual page (man7.org)

Hardware exception mechanisms are processed by the CPU. It is intended to support, e.g., error detection, and redirects the program flow to error handling service routines. The state before the exception is saved, e.g., on the stack.

Exception handling in the IEEE 754 floating point hardware 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. 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.

In 1996 the maiden flight of the Ariane 5 (Flight 501) ended in a catastrophic explosion due in part to the Ada programming language exception handling policy of aborting computation on arithmetic error, which in this case was a 64-bit floating point to 16-bit integer conversion overflow. The official report on the crash (conducted by an inquiry board headed by Jacques-Louis Lions) noted that "...The supplier of the inertial navigation system (SRI) was only following the specification given to it, which stipulated that in the event of any detected exception the processor was to be stopped. The exception which occurred was not due to random failure but a design error. The exception was detected, but inappropriately handled because the view had been taken that software should be considered correct until it is shown to be at fault..."

inertia

  1. the force that keeps an object in the same position or keeps it moving until it is moved or stopped by another force
  2. a lack of energy and a feeling that you do not want to do anything
  3. when no one wants to do anything to change a situation

Unix-like operating systems provide facilities for handling exceptions in programs via IPC. Typically, interrupts caused by the execution of a process are handled by the interrupt service routines of the operating system, and the operating system may then send a signal to that process, which may have asked the operating system to register a signal handler to be called when the signal is raised, or let the operating system execute a default action (like terminating the program). Typical examples are SIGSEGV, SIGBUS, SIGILL and SIGFPE.

signal(7) - Linux manual page (man7.org)

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".

From the point of view of the author of a routine [例程; 例行公事], raising an exception is a useful way to signal that a routine could not execute normally - for example, when an input argument is invalid (e.g. value is outside of the domain of a function) or when a resource it relies on is unavailable (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. In systems without exceptions, routines would need to return some special error code. However, this is sometimes complicated by the semipredicate problem, in which users of the routine need to write extra code to distinguish normal return values from erroneous ones.

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 what the result means in this case. For exammple, the division operation yields a real number, but fails when the divisor is zero. If we were to write a function that performs division, we might choose to return 0 on this invalid input. However, if the dividend is 0, the result is 0 too. This means there is no number we can return to uniquely signal attempted division by zero, since all real numbers are in the range of division. A subroutine is a self-contained section of a computer program for performing a specific task. 子程序; 子例程。

  • Sub- is used at the beginning of words that have 'under' as part of their meaning.
  • Sub- is added to the beginning of nouns in order to form other nouns that refer to things that are part of a larger thing.
  • Sub- is added to the beginning of adjectives in order to form other adjectives that describe someone or something as inferior.

It's possible to represent values that aren't real numbers, such as 0 / 0, in the IEEE floating-point format. A value of this kind is called a NaN [Not a Number]. A NaN is represented by an exponent of all ones and a non-zero significand.

IEEE Floating-Point Representation - Microsoft Docs

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: Java, Python and Ruby fall in this category.
  • Languages where exceptions are only used to handle abnormal, unpredictable, erroneous situations: C++, C#, and Common Lisp.

Software exception handling developed in Lisp in the 1960s and 1970s. This originated in LISP 1.5 (1962), where exceptions were caught by the ERRSET keyword, which returned NIL in case of an error, instead of terminating the program or entering the debugger.

A contrasting view on the safety of exception handling was given by Tony Hoare in 1980, describing the Ada programming language 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."

  • plethora [Origin: Greek, 'fullness', from plethein 'to be full']
  • plentiful, plenty, excessive, extravagant

Sir Charles Antony Richard Hoare FRS FREng is a British computer scientist who has made foundational contributions to programming languages, algorithms, operating systems, formal verification, and concurrent computing. His work earned him the Turing Award, usually regarded as the highest distinction in computer science, in 1980. FREnd: Fellowship of the Royal Academy of Engineering.

Exception handling is often not handled correctly in software, especially when there are multiple sources of exceptions; data flow analysis 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".

Go was initially released with exception handling explicitly omitted, with the developers arguing that it obfuscated control flow. Later, the exception-like panic/recover mechanism was added to the language, which the Go authors advise using only for unrecoverable errors that should halt the entire process.

Exceptions, as unstructured flow, increase the risk of resource leaks (such as escaping a section locked by a mutex, or one temporarily holding a file open) or inconsistent state. There are various techniques for resource management in the presence of exceptions, most commonly combining the dispose pattern with some form of unwind protection (like a finally clause), which automatically releases the resource when control exits a section of code.

Recent front-end web frameworks, such as React and Vue, 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.[

The implementation of exception handling in programming languages typically involves a fair amount of support from both a code generator and the runtime system accompanying a compiler. (It was the addition of exception handling to C++ that ended the useful lifetime of the original C++ compiler, Cfront.) Two schemes are most common. The first, dynamic registration, generates code that continually updates structures about the program state in terms of exception handling.

The second scheme, and the one implemented in many production-quality C++ compilers, is a table-driven approach. This creates static tables at compile time and link time that relate ranges of the program counter 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. This second approach is also superior in terms of achieving thread safety.

六级/考研单词: compute, execute, norm, hardware, implement, construct, interrupt, grace, resume, abnormal, alternate, implicit, auxiliary, globe, invariable, float, valid, filter, manual, detect, stack, default, substitute, nil, trap, maiden, explode, abort, arithmetic, convert, overflow, crash, conduct, inquiry, inertia, navigate, stipulate, random, situate, terminate, differ, denote, data, author, domain, missing, complicate, yield, dividend, noun, adjective, inferior, exponent, contemporary, convention, rocket, astray, excess, extravagant, verify, concurrent, fellow, academy, seldom, multiple, million, defect, cite, omit, panic, advice, halt, leak, disposition, web, propagate, component, hierarchy, dynamic, perpetual, update, static, compile, instruct, overhead, allocate, superior, thread

posted @ 2022-08-12 19:40  华容道专家  阅读(47)  评论(0)    收藏  举报