Exception handling (programming)

Uses your system voice; voice and rate in settings.

Snapshot

≈ 11 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

In computer programming, several programming language mechanisms exist for exception handling. The term exception is typically used 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.

In computer programming, several programming language mechanisms exist for exception handling. The term exception is typically used 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. import java.io.IOException; import java.util.Scanner; try { Scanner stdin = new Scanner(System.in); String line = stdin.nextLine(); if (line.length() == 0) { throw new IOException("The line read from console was empty!"); } System.out.printf("Hello %s!%n", line); System.out.println("The task executed successfully."); } catch (IOException e) { System.out.println("Hello!"); } catch (Exception e) { System.out.printf("Error: %s%n", e.getMessage()); } finally { System.out.println("The program is now terminating."); } C does not have try-catch exception handling, but uses return codes for error checking. The setjmp and longjmp standard library functions can be used to implement try-catch handling via macros. Perl 5 uses die for throw and for try-catch. It has CPAN modules that offer try-catch semantics. 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)." C++26 adds support for contracts, which are used as follows. int f(const int x) pre(x != 1) // a precondition assertion post(r : r == x && r != 2) // a postcondition assertion; r names the result object of f { contract_assert(x != 3); // an assertion statement return x; } import java.io.File; import java.io.IOException; import java.util.zip.DataFormatException; // Indicates that IOException and DataFormatException may be thrown public void operateOnFile(File f) throws IOException, DataFormatException { // ... } According to Hanspeter Mössenböck, checked exceptions are less convenient but more robust. Checked exceptions can, at compile time, 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 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 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 throws Exception declaration. Another circumvention is to use a try { ... } catch (Exception e) { ... } (or even a try { ... } catch (Throwable t) { ... } ) handler. This is referred to as catch-all exception handling or Pokémon exception handling after the show'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 java.lang.RuntimeException , thus making the exception unchecked. 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 java.lang.Throwable . 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. Kotlin lacks checked exceptions, and even throwing a Java checked exception from Kotlin will not force the client to handle it from Java. However, this can be enabled using the @Throws annotation, which will emit the throws metadata to the JVM. For example, consider the following Kotlin code: import java.io.IOException @Throws(IOException::class) fun readFile() { // ... throw IOException("Failed to read file!") } This would translate roughly back to the following in the JVM: import java.io.IOException; public static final void readFile() throws IOException { // ... throw new IOException("Failed to read file!"); } In C#, an experimental specification, Spec#, released by Microsoft, implements checked exceptions, with a throws clause; all checked exceptions must implement the Microsoft.Contracts.ICheckedException interface. include using std::domain_error; using std::invalid_argument; // this could be similar to the Java signature // void performSomeOperation(int a, int b) throws InvalidArgumentException, ArithmeticException; void performSomeOperation(int a, int b) throw(invalid_argument, domain_error) { // ... } C++ throw clauses could specify any number of any types, even primitives and classes that did not extend std::exception (because C++ supports throwing objects of any type). If no type was named in the throw clause, it would indicate that the function would not throw at all. Exception specifications were not enforced at compile-time. Violations resulted in the standard library function std::unexpected() being called. 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 and C++03, deprecated in the 2012 C++ language standard (C++11), and was removed from the language in C++17. Throws clauses were replaced by clauses. A function that will not throw any exceptions would now be denoted by the keyword, and instead specified that a function will throw. Although throw clauses are removed from the language, writing only throw() in the signature is legal and is equivalent to noexcept (no exception specified by the throw clause denotes that it cannot throw), however this is still considered deprecated. For transitioning a codebase that uses throw clauses, the removed throw can be redefined as a macro. This is only a temporary fix to allow the code to compile, rather than an actual implementation of checked exceptions. Using this, one can similarly imitate Java throws clauses. // If throw() is empty, it expands to noexcept(true) (same as noexcept), // otherwise it expands to noexcept(false). // A throw statement without parentheses will not expand define throw(...) noexcept(__VA_OPT__(!)true) import std; using std::runtime_error; class FooException : public runtime_error {}; class BarException : public runtime_error {}; // throw(Es...) will expand into noexcept(false) void performSomeOperation(int x, int y) throw(FooException, BarException) { if (x > y) { // throw without a bracket will not expand as a macro throw FooException("x > y"); } else if (y > x) { throw BarException("y > x"); } std::println("x = y = {}", x); } // throw() will expand into noexcept(true) void willNotThrow(int x) throw() { std::println("x = {}", x); } One can also specify that a function is noexcept conditionally on another function being noexcept , like so: void mightThrow(); // The first noexcept is the noexcept clause, the second is the noexcept operator which evaluates to a Boolean value void f() noexcept(noexcept(mightThrow())); Though C++ has no checked exceptions, one can propagate the thrown object up the stack when inside a catch block, by writing (without specifying an object). This re-throws the caught object. This allows operations to be done within the catch block that catches it, before choosing to allow the object to continue propagating upwards. An uncaught exceptions analyzer exists for the OCaml 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). In C++, one can also perform "Pokémon exception handling". Like catch (Throwable t) in Java, C++ supports a catch (...) block, which will catch any thrown object. However, catch (...) has the disadvantage of not naming the caught object, which means it cannot be referred to. This is because in languages like Java, only classes which extend java.lang.Throwable may be thrown, while in C++ any type (even primitives) may be thrown, and thus there is no guaranteeably safe way to store a reference to the caught object of a catch-all block. import std; using std::exception; // Catching only exceptions: try { // ... } catch (const exception& e) { // Catching only exceptions: std::println("An exception was caught: {}", e.what()); } catch (...) { // Catching all thrown objects: std::println("An unknown error was caught"); } The Rust language, instead of using exceptions altogether, represents recoverable exceptions as result types. This is represented as Result (or expected in C++). The advantage of result types over checked exceptions is that while both result types and checked exceptions force users to immediately handle errors, they can also be directly represented as a return type within the language's type system, unlike checked exceptions where the declared potentially thrown exception is part of the function signature but not directly part of its return type. The Rust language does not have exceptions. It instead uses (a result type) for handling runtime errors, and for serious errors the macro is used. Although Rust avoids the try / catch mechanism common in most exception handling languages, it still allows for catching panics, using the std::panic::catch_unwind() function, as the default behavior in Rust when a panic occurs is to perform stack unwinding.

See also

Automated exception handling Continuation Defensive programming Exception safety Option types and Result types, alternative ways of handling errors in functional programming without exceptions

Notes

References

Works cited

Text derived from https://en.wikipedia.org/w/index.php?oldid=1378995886 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

27 named source(s) extracted from the cited revision. A source with no author is shown by its publication; nothing is invented.