Exception handling: Difference between revisions

Content deleted Content added
move some things into syntax section
mNo edit summary
Line 1:
{{Short description|Programming language construct for special conditions}}
{{redirectRedirect-distinguish|Error handling|Error detection and correction}}
{{aboutAbout|computing|knowledge|fact checking|and|problem solving}}
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 [[Computer program|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 [[Computer hardware|hardware]] or [[software]] exception and how the software exception is implemented. Exception handling, if provided, is facilitated by specialized [[programming language]] constructs, hardware mechanisms like [[interrupt]]s, or [[operating system]] (OS) [[inter-process communication]] (IPC) facilities like [[Signal (IPC)|signals]]. 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 [[Subroutine|procedure]] has a [[precondition]], a set of circumstances for which it will terminate "normally".<ref name=Cristian>{{cite journal |last1=Cristian |first1=Flaviu |title=Exception Handling and Software Fault Tolerance |journal=Proc. 10th Int. Symp. On Fault Tolerant Computing|date=1980 |issue=6 |pages=531–540 |doi=10.1109/TC.1982.1676035|citeseerx=10.1.1.116.8736|s2cid=18345469 |oclc=1029229019|edition=FTCS-25 reprint}}</ref> An exception handling mechanism allows the procedure to ''raise an exception''{{sfn|Goodenough|1975b|pp=683-684}} if this precondition is violated,<ref name=Cristian/> for example if the procedure has been called on an abnormal set of arguments. The exception handling mechanism then ''handles'' the exception.{{sfn|Goodenough|1975b|p=684}}
The precondition, and the definition of exception, is [[Subjectivity|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).{{sfn|Black|1982|pp=13-15}} Common exceptions include an invalid argument (e.g. value is outside of the [[___domain of a function]]), 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.
Line 36 ⟶ 35:
There is no clear consensus as to the exact meaning of an exception with respect to hardware.<ref>{{cite web |last1=Hyde |first1=Randall |title=Art of Assembly: Chapter Seventeen |url=https://www.plantation-productions.com/Webster/www.artofasm.com/DOS/ch17/CH17-1.html#HEADING1-0 |website=www.plantation-productions.com |access-date=22 December 2021}}</ref> From the implementation point of view, it is handled identically to an [[interrupt]]: the processor halts execution of the current program, looks up the [[interrupt handler]] in the [[interrupt vector table]] for that exception or interrupt condition, saves state, and switches control.
 
== IEEE 754 floating -point exceptions ==
Exception handling in the [[IEEE 754]] [[floating point#Dealing with exceptional cases|floating point]] 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."
 
Line 121 ⟶ 120:
 
=== 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]] accompanying a compiler. (It was the addition of exception handling to C++ that ended the useful lifetime of the original C++ compiler, [[Cfront]].<ref>[[Scott Meyers]], [http://www.artima.com/cppsource/top_cpp_software.html The Most Important C++ Software...Ever] {{webarchive|url=https://web.archive.org/web/20110428221802/http://www.artima.com/cppsource/top_cpp_software.html |date=2011-04-28 }}, 2006</ref>) Two schemes are most common. The first, ''{{visible anchor|dynamic registration}}'', generates code that continually updates structures about the program state in terms of exception handling.<ref>D. Cameron, P. Faust, D. Lenkov, M. Mehta, "A portable implementation of C++ exception handling", ''Proceedings of the C++ Conference'' (August 1992) [[USENIX]].</ref> Typically, this adds a new element to the [[Call stack|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]] (SEH) uses this approach with a separate exception stack.<ref>{{cite web|url=http://stoned-vienna.com/html/index.php?page=windows-exception-handling|author=Peter Kleissner|title=Windows Exception Handling - Peter Kleissner|date=February 14, 2009|access-date=2009-11-21 |archive-url=https://web.archive.org/web/20131014204335/http://stoned-vienna.com/html/index.php?page=windows-exception-handling |archive-date=October 14, 2013 |url-status=dead}}, ''Compiler based Structured Exception Handling'' section</ref> Dynamic registration, being fairly straightforward to define, is amenable to [[proof of correctness]].<ref>Graham Hutton, Joel Wright, "[http://www.cs.nott.ac.uk/~gmh/exceptions.pdf Compiling Exceptions Correctly] {{webarchive|url=https://web.archive.org/web/20140911173720/http://www.cs.nott.ac.uk/~gmh/exceptions.pdf |date=2014-09-11 }}". ''Proceedings of the 7th International Conference on Mathematics of Program Construction'', 2004.</ref>
 
Line 183 ⟶ 181:
 
=== Checked exceptions ===
 
[[Java (programming language)|Java]] introduced the notion of checked exceptions,<ref>{{cite web |url=http://answers.google.com/answers/threadview?id=26101 |title=Google Answers: The origin of checked exceptions |access-date=2011-12-15 |url-status=live |archive-url=http://archive.wikiwix.com/cache/20110806090553/http://answers.google.com/answers/threadview?id=26101 |archive-date=2011-08-06 }}</ref><ref>Java Language Specification, chapter 11.2. http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#11.2 {{webarchive|url=https://web.archive.org/web/20061208042454/http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html |date=2006-12-08 }}</ref> which are special classes of exceptions. The checked exceptions that a method may raise must be part of the method's [[Type signature|signature]]. For instance, if a method might throw an {{Java|IOException}}, 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.<ref>{{cite web
|access-date = 2011-08-05
Line 224 ⟶ 221:
 
=== Asynchronous exceptions ===
 
'''Asynchronous exceptions''' are events raised by a separate thread or external process, such as pressing [[Control-C|Ctrl-C]] to interrupt a program, receiving a [[Signal (computing)|signal]], or sending a disruptive message such as "stop" or "suspend" from another [[Thread (computer science)|thread of execution]].<ref>{{cite web |url=http://citeseer.ist.psu.edu/415348.html |title=Asynchronous Exceptions in Haskell - Marlow, Jones, Moran (ResearchIndex) |publisher=Citeseer.ist.psu.edu |access-date=2011-12-15 |url-status=live |archive-url=http://archive.wikiwix.com/cache/20110223164151/http://citeseer.ist.psu.edu/415348.html |archive-date=2011-02-23 }}</ref><ref>{{cite journal|url=http://www.cs.williams.edu/~freund/papers/python.pdf |title=Safe Asynchronous Exceptions For Python |access-date=4 January 2022 |first1=Stephen N.|last1=Freund|first2=Mark P.|last2=Mitchell }}</ref> Whereas synchronous exceptions happen at a specific <code>throw</code> 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.
 
Line 230 ⟶ 226:
 
=== Condition systems ===
[[Common Lisp]], [[Dylan (programming language)|Dylan]] and [[Smalltalk]] have a [[condition system]]<ref>{{cite web|author = What Conditions (Exceptions) are Really About|url = http://danweinreb.org/blog/what-conditions-exceptions-are-really-about|title = What Conditions (Exceptions) are Really About|publisher = Danweinreb.org|date = 2008-03-24|access-date = 2014-09-18|url-status = dead|archive-url = https://web.archive.org/web/20130201124021/http://danweinreb.org/blog/what-conditions-exceptions-are-really-about|archive-date = February 1, 2013}}</ref> (see [[Common Lisp#Condition system|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]]) 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.<ref>{{cite web |url=http://www.franz.com/support/documentation/6.2/ansicl/section/conditio.htm |title=Condition System Concepts |publisher=Franz.com |date=2009-07-21 |access-date=2011-12-15 |archive-url=https://web.archive.org/web/20070628213221/http://www.franz.com/support/documentation/6.2/ansicl/section/conditio.htm |archive-date=2007-06-28 |url-status=dead }}</ref>
Line 247 ⟶ 243:
 
=== Criticism ===
 
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.<ref name="toplas2008">{{cite news|author1=Weimer, W|author2=Necula, G.C.|title=Exceptional Situations and Program Reliability|journal=ACM Transactions on Programming Languages and Systems |volume=30 |issue=2|url=http://www.cs.virginia.edu/~weimer/p/weimer-toplas2008.pdf|year=2008|url-status=live|archive-url=https://web.archive.org/web/20150923211739/http://www.cs.virginia.edu/~weimer/p/weimer-toplas2008.pdf|archive-date=2015-09-23}}</ref>
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".<ref name="toplas2008"/>{{rp|8:27}} "While try-catch-finally is conceptually simple, it has the most complicated execution description in the language specification [Gosling et al. 1996] and requires four levels of nested “if”s in its official English description. In short, it contains a large number of [[corner cases]] that programmers often overlook."<ref name="toplas2008"/>{{rp|8:13–8:14}}